I want return correct json structure from my server.
I tried this, but in response I had a string:
string jsonDataStructure = "[{\"Field1\": 1, \"Fieald2\":true}, {\"Field1\": 1, \"Fieald2\":true}]";
return new JObject(
new JProperty("MyData", jsonDataStructure)
);
How can I get my JSON data with a write data structure?
Edit :- If your string is a serialization of an object say jsonResponse, you would do
return Ok(jsonResponse)
. However if it is a string you would do
return Ok(JObject.Parse(jsonDataStructure))
. That should solve your problem.
First of all, I couldn't really get the gist of this question, so I'm going to say change your return statement to this.
return JObject.Parse(jsonDataStructure);
If you are trying to send an object, I would recommend serializing it using libraries like "newtonsoft.json". If not, you may also wrap the data you want to send in an object and still use the library
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;
I have stored a variable as TempData["ReqNo"]
ViewBag.TransNum = TempData["ReqNo"];
TempData.Keep();
I have a jQuery DataGrid Table that I populate with
var q = db.ICS_Orders;
I have been trying to add a WHERE Clause using the value of TempData but no matter what I try, I cannot get it to work. I have looked all over, online, and found very little help.
Was hoping someone could just give me a quick example of how to use TempData in linq. I have the following
var currReq = TempData["ReqNo"];
q = q.Where(s => s.RequisitionNumber.Contains(currReq)).ToList();
The above is one of MANY variations I have tired. With the above, I am getting the error "cannot convert object to string"
I tried to convert using .
Convert.ToString(currReq);
But that didn't help at all.
And to answer the question on everyone's mind :Why are you doing it like this?
Because, I am a newbie and I am finding my way. I usually try to figure things out the best I can before asking for help. I really can't find much information about using TempData values in linq online.
Thank you
To get variables back out of TempData, cast them back to their original type. So if TempData["ReqNo"] was assigned a string, you can get it back out with:
var currReq = (string)TempData["ReqNo"];
Convert.ToString(foo) or foo.ToString() are for getting the string representation of a non-string object. Since the object in TempData["ReqNo"] was originally a string, you don't need to use a convert function, just a cast back to the original type.
My webs service is returning a DateTime to a jQuery call. The service returns the data in this format:
/Date(1486308595040)/
I am getting multiple data from table of database i have seen many articles on this and they answered this:
var d = new Date();
d.setTime(1245398693390);
document.write(d);
But i have 1000 or more records from that answer i have to do get each row and convert it into json friendly data that is not a suitable.
My Code :
var history = db.v_recharge_payment_History.Where(x => x.RCV_UID == loginQuery.ID).OrderByDescending(x => x.RCV_ID).Take(10).ToArray();
dictionary.Add("result", 200);
dictionary.Add("data", history);
return Json(dictionary, JsonRequestBehavior.AllowGet);
How can I convert this into a JavaScript-friendly date without iterate each row ?
Don't use the JavascriptSerializer to generate the JSON. the Controller.Json() method uses the built-in JavaScriptSerializer, which has many problems besides the weird date serialization. Instead, inherit JsonResult, and reimplement using Newtonsoft Json.NET. I won't give an example here because this is an old problem and you should be able to find plenty of examples on the web for that.
Use Newtonsoft JSON serializer and annotate your DateTime property with
[JsonConverter(typeof(JavaScriptDateTimeConverter))]
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.