I'm trying to define aoColumns using ajax and a C# webmethod. I am treating it very similarly to how I am passing in server-side data, using a List> data structure that I add rows of List to. My problem is that this results in a string like:
{\"aoColumns\":[[\"\\\"bVisible\\\": False\"],[\"\\\"bVisible\\\": True\"],[\"\\\"bVisible\\\": True\"],[\"\\\"bVisible\\\": True\"],[\"\\\"bVisible\\\": True\"],[\"\\\"bVisible\\\": True\"],[\"\\\"bVisible\\\": True\"],[\"\\\"bVisible\\\": True\"]]}
Which is nearly correct, except that the column definitions are using square brackets instead of {}. How would I go about generating the correct JSON text? Any help is greatly appreciated!
I am assuming you are using data tables from http://www.datatables.net/. Please correct me if I am wrong.
I am not sure I understand if you are having trouble creating the JSON string to return to the AJAX call or converting it into something usable on the server-side.
If you are going to create a JSON string in a web method, I would suggest using a Dictionary type, since they are so close to JSON strings. To convert a Dictionary type into a JSON string, use this:
var dictionary = new Dictionary<string, string>()
// add values here...
return new JavaScriptSerializer().Serialize(dictionary);
If you are converting a JSON string into a Dictionary object, use this:
var dictionary = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(jsonString);
Another thing I like to do is convert the dictionary into an array if I am going to be working with any keys or values since getting them from the dictionary can be a pain when you do not know the exact key value you want to work with.
For reference, the JavaScriptSerializer is part of the System.Web.Script.Serialization.JavaScriptSerializer namespace and in the System.Web.Extensions assembly.
Related
Recently I've gotten into JSON parsing, and I was wondering, is it at all possible to completely dynamically load all of the contents within a JSON file? And by dynamically load, I mean, load all values of a JSON file without knowing any keys, meaning I cannot do the following code:
string contents = File.ReadAllText("SomeJsonFile.txt");
JObject obj = JObject.Parse(contents);
var value = obj["SomeKey"];
The reason I cannot do the code above, is because that would require the application to know the key ahead of time.
My goal is to be able to load any JSON file, and retrieve all values from said JSON file. I want to be able to load nested values, along with root values, all without knowing the keys.
Is there a way for me to do this? If you need any more information, please don't hesitate to ask.
The way I want to use this data is to first, bind a textbox to a string version of each key. Then I will dynamically add the TextBoxes to a FlowLayoutPanel, I also want the user to be able to change this data, and the JSON to change with it.
Please help.
If you don't know what the keys you are going to have you can use JArray from Json.NET to dynamically access the class.
See example instantiation and usage in the answer here:
How to access elements of a JArray (or iterate over them)
Assuming the JSON is an object and not an array, you could deserialize the json string to a IDictionary<string, object> using Json.NET
string myJsonString = File.ReadAllText("SomeJsonFile.txt");
var dataObj = JsonConvert.DeserializeObject<IDictionary<string, object>>(myJsonString);
var topLevelKeys = dataObj.Keys;
Your original question already shows you've successfully parsed a JSON string into a C# object, without knowing the keys.
It appears your actual question is on how to flatten the JObject into some kind of enumerable set of key/value pairs. For that, I refer you to the answers on this thread:
Generically Flatten Json using c#
Answer 2 IMO looks a lot cleaner:
string contents = File.ReadAllText("SomeJsonFile.txt");
var schemaObject = JObject.Parse(contents);
var values = schemaObject
.SelectTokens("$..*")
.Where(t => !t.HasValues)
.ToDictionary(t => t.Path, t => t.ToString());
In my Xamarin.Forms app I use a socket.IO library that fetches data from a Node.js server but I don‘t know about extracting the data from my result. The example method looks like this:
socket.On("event", (data) =>
{
Console.WriteLine(data);
});
When the result is a simple string, I can directly use it as in the console function above.
But how do I extract the data when the result is a unknown datatype that contains multiple information, like this?
let send = {'firstString': string1, 'secondString': string2}
I guess a way could be to make the result a JSON object and read it out by it‘s keys but I don‘t know if that’s a good way and how this would be done.
use Json.Net to parse the json
JObject obj = JObject.Parse(data);
var first = obj["firstString"].Value;
var second = obj["secondString"].Value;
var details= _clientService.GetAsync<DoctorDetails>(getDetails).Result;
I get the Result from the service which is JSON when I use "object" in the GetAsync instead of DoctorDetails. However, I don't see any property values being filled in details (All are null in DoctorDetails). DoctorDetails is the cs file of the schema I generated through xsd.
DoctorDetails is an auto generated file that contains properties like
Name
ID etc
How to deserialize this and get values in those properties (in the details variable above)
Edit
It is only returning values if I make the syntax like this
var details= _clientService.GetAsync<object>(getDetails).Result;
If you haven't already tried this option, use a library called Json.Net from Newtonsoft for json stuff. Newtonsoft json.
Provided you have the schema details and the property names match you may try the following..
var details= _clientService.GetAsync<object>(getDetails).Result;//Please check if this is a string else use .ToString()
/*
"{
'Name': 'Doctor Who',
'ID' : '1001'
}";
*/
DoctorDetails m = JsonConvert.DeserializeObject<DoctorDetails>(details);
Documentation Deserialize an Object.
I'm not promoting this library, it's just a suggestion. :)
Hope it helps.
I am dynamically building the colModel for my jQGrid using fields from a DataTable. Nearly all of it works as I hoped. However, I am unable to use a custom summaryType because I can't serialize without the quotes and jQgrid doesn't look for the method if in quotes.
Presently, if I don't remove the ", I get the following error when loading the grid:
Uncaught jqGrid Grouping No such method: mysum
If I remove the quotes in the table, I get the following error when serializing:
Invalid JSON primitive: mysum.
What is the best way to tackle this problem?
You will probably have to create a solution in the view using javascript. If you manually serialize the colModel to send to the view, you will have to manually deserialize. You will not be able to parse it with a JSON parser because it will not be a valid JSON string.
One possible approach would be to use eval() on the string like this:
myObject.property = eval("mysum");
It should replace the string with the function. I am not sure if it meets your needs, but will avoid both errors you listed above.
The overall objective is to get a Json representation of the query results of the SqlQuery executed. This Json will be used to create visualizations/reports on the browser using js based charting tools.
Now, controls like gridview are able to read the column names as well as the data and give us an html representation of the data. So I think it should be possible to write code such that it can read from a sql data reader and come up with a json representation.
I could not find anything in my searches which does what I want. How do I go about doing this? any pointers?
You could use an SqlDataAdapter to fill a DataSet. This blog post describes a way of converting a DataTable or DataSet into its JSON representation.
You could use the Json.Net serializer. It supports serializing a Dictionary<string,object> to a JSON object.
Another big shot would be using NHibernate and serializing the resulting objects.
Here is another link to using the Json.Net serializer for DataSets:
If you scroll down to the comments on this page you see a much shorter solution using the Dictionary approach.