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))]
Related
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 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
I have created a web service using JSON and REST. What I want to know is how to output contents of a local database using the service?
I am using Visual Studio 2015, ASP.NET Web Forms and LINQ data source.
I think I have to use some c# code as well to get this working but I am not sure.
I have tried different approaches but cannot seem to find the right solution.
I was spending some time on the following but it is not what i am looking for...
http://williamsportwebdeveloper.com/cgi/wp/?p=494
Take a look at the Newtonsoft.Json package available freely on NuGet.
You can use the Newtonsoft.Json.JsonConvert.SerializeObject(object) method to return a JSON representation of the object parameter provided as a string.This can be returned to the user of the web service as is.
Since you're using LINQ, I'm assuming you've got your data structure set up including classes, so you can make a connection to the database, process the results to create your objects, and finally use the SerializeObject(object) method to serialize the root object as JSON to be returned to the user of the web service.
See if this help:
http://andre-pedroso.blogspot.pt/2013/03/endpoint-on-aspnet-page-returning-json.html
It isn´t from an IQueryable but from a DataTable, but the return type is what you looking for.
[System.Web.Services.WebMethod]
public static string GetData()
{
DataTable dt = GetDataTable();
return BuildJSONFromDT(dt);
}
private static string BuildJSONFromDT(DataTable dt)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<object> resultMain = new List<object>();
foreach (DataRow row in dt.Rows)
{
Dictionary<string, object> result = new Dictionary<string, object>();
foreach (DataColumn column in dt.Columns)
{
result.Add(column.ColumnName, "" + row[column.ColumnName]);
}
resultMain.Add(result);
}
return serializer.Serialize(resultMain);
}
Cheers!
If I have understood correctly, You want to output LINQ data to JSON.
First convert LINQ to datatable using code presented here
Convert DataTable to JSON using the method detailed here
Also a similar question on DataTable to JSON is answered here
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.
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.