Convert dictionary object to string to output as json - c#

I am using razor in webmatrix.
I have a dictionary object
var occupancyTotalDic = new Dictionary<double, int>();
Once I have filled the dictionary with data I wish to output as JSON as a response to populate a flot chart
Dictionary<String, String> input = new Dictionary<String, String>();
occupancyTotalDic = input.ToDictionary(item => item.Key, item => (String)item.Value);
Response.ContentType = "application/json";
Response.Write(Json.Encode(occupancyTotalDic));
How do I convert my dictionary to contain strings so that I can output as JSON?

Since Webmatrix can't compile MVC application I assume you are using ASP.NET webforms.
Tried this solution https://stackoverflow.com/a/5597628/713789
If you are using MVC then just use JsonResult test(){ return Json(myobj);}

Related

How to output request headers to a string in C#

I would like to add two custom headers for a DELETE request to a string.
I have the following code
Dictionary<string, string> customHeaders = new Dictionary<string, string>();
customHeaders.Add("If-Match", passedEtag);
customHeaders.Add("context_study_site", "edc42643-27b5-428e-b8ae-2fa19bfb457a");
I have tried the following
StringBuilder sb = new StringBuilder();
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine + "Context headers passed in the request" + Environment.NewLine);
Dictionary<string, string> customHeaders = new Dictionary<string, string>();
customHeaders.Add("If-Match", passedEtag);
customHeaders.Add("context_study_site", "edc42643-27b5-428e-b8ae-2fa19bfb457a");
string test = customHeaders.ToString();
File.WriteAllText("C:\\Testing", "headersoutput.txt");
But I get the following
System.Collections.Generic.Dictionary`2[System.String,System.String]
System.Collections.Generic.Dictionary`2[System.String,System.String]
Rather than the two header key value pairs.
Any ideas much appreciated.
Thanks in advance.
Instead of .ToString() you need to Serialize your dictionary using JsonConvert.SerializeObjec()
var jsonDict = JsonConvert.SerializeObject( myDictionary );
Then write it to a file,
File.WriteAllText(#"C:\Testing\headersoutput.txt", jsonDict);
Why you are getting System.Collections.Generic.Dictionary2[System.String,System.String] in the your file?
You are trying to convert a Dictionary to string using
.ToString() method. You are not overriding its basic functionality,
so it calls the basic implementation of .ToString() method present
in Object class.
Returns a string that represents the current object.
MSDN: Basic implementation of Object.ToString()
How we solved it?
We used JsonConvert.SerializeObject() method from
Newtonsoft.Json library, which convert object(In your case
it is a dictionary), to a json string
Serializes the specified object to a JSON string.

Request.Form serialize to JSON and loop through all properties in JSON

I have .NET Core Web API project and one API query that accepts random form data (without files). I need to serialize form data to JSON and pass to the service. Then in service I need to loop through each JSON property and do some handling.
I'm trying something like this:
var json = JsonConvert.SerializeObject(Request.Form); //it isn't simple JSON
and
var jsonObject = new JObject();
var data = Request.Form.ToList();
for (var i = 0; i < data.Count; i++)
{
jsonObject.Add(data[i].Key, data[i].Value.ToString());
}
Are there any other ways to do that? What about loop through all JSON properties?
I am not sure you can serialize directly Request.Form to JSON.
But could you try like this way ?
public static IDictionary<string, object> ToDictionary(this NameValueCollection col)
{
var dict = new Dictionary<string, object>();
foreach (var key in col.Keys)
{
dict.Add(key, col[key]);
}
return dict;
}
then
var dictionary = Request.Form.ToDictionary();
string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
then on the service deserialize your string.
Dictionary<string, object> dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

How to convert a string json to a dictionary in C#

I have a simple WinForm program that does a WebRequest to a server, the response is a string looking like:
{"a":"foo","b":"bar"}
How do convert this string to a dictionary? (Dictionary<string, string>). Is there a built-in function I can use?
Use a library like JSON.NET:
var dictionary = JsonConvert.DeserializeObject<IDictionary<string, string>>(json)
var sourve = #"{"a":"foo","b":"bar"}";
Dictionary<string, string> result = JsonConvert.DeserializeObject<Dictionary<string, string>>(source);
If you can add two assemblies:
System.Web
System.Web.Extensions
You can use this code:
string html = "{\"a\":\"foo\",\"b\":\"bar\"}";
JavaScriptSerializer jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string, string>>(html);

Inserting a Row in BigQuery with Nested Record using C# API

I'm trying to insert a row (with nested records) into BigQuery using the C# API. I'm able to insert a row (w/ nested records) using the JavaScript API. But using the C# API i'm getting error saying: "Repeated field must be imported as a JSON Array". He is a simple row that I was able to insert using the JavaScript API
var json = {'rows':[{'json':
{"inputs" : [{
"Age":"10"
}]}}]};
This works fine in JS, but I'm unclear how to do this in C#.
Here is my attempt:
var r = new TableDataInsertAllRequest.RowsData();
r.Json = new Dictionary<string, object>();
var dict = new Dictionary<string, object>();
dict.Add("Age", "10");
r.Json.Add("inputs", dict);
Also I tried using JSON API
string json = JsonConvert.SerializeObject(input, jsonSettings);
var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json, jsonSettings);
r.Json.Add("jsonInputs", dict);
Here is the API Doc for RowsData https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/csharp/latest/classGoogle_1_1Apis_1_1Bigquery_1_1v2_1_1Data_1_1TableDataInsertAllRequest_1_1RowsData.html
Its somewhat vague or unclear how to do nested records. I tried just writing straight JSON but getting the same errors.
Any help would be much appreciated.
Thanks,
From the json example that works there are two arrays. I don't see any arrays in either of two failing examples you provide.
I suspect adding the arrays will fix your problem. Consider parsing the known-working json string into a json object and using that as a quick test.
The following code snippet successfully works for bigquery:
JArray inputs = new JArray();
JObject inputOne = new JObject(new JProperty("Age", "12"));
inputOne.Add(new JProperty("BirthDate", "1234"));
r.Json.Add("inputs", inputs);

Converting wikipedia api response using Json.net

I'm querying data using wikipedia api and would like to convert the result into a string[].
The query "test"
en.wikipedia.org/w/api.php?action=opensearch&search=test&format=json&callback=spellcheck
returns this result here:
spellcheck(["test",["Test cricket","Test","Testicle","Testudines","Testosterone","Test pilot","Test (assessment)","Testimonial match","Testimony","Testament (band)"]])
Can I use Json.net to drop or ignore the tag "spellcheck"?
If I convert the response using this code, the application crashes:
Dictionary<string, string[]> dict = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(response);
Wikipedia's api (using JSON) assumes you're using JSONP. You could just drop the callback parameter completely from your query string:
en.wikipedia.org/w/api.php?action=opensearch&search=test&format=json
Additionally, the result you're getting probably cannot be converted into a Dictionary<string, string[]>. If you look closely, it's actually an array where the first object is a string (search term) and the second is a list of strings (results).
The following worked for me:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(
#"http://en.wikipedia.org/w/api.php?action=opensearch&search=test&format=json");
string[] searchResults = null;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
JArray objects = JsonConvert.DeserializeObject<JArray>(reader.ReadToEnd());
searchResults = objects[1].Select(j => j.Value<string>()).ToArray();
}
}

Categories

Resources