I am using c#.
Now I am looking to create a "JSONHelper" class, which will Serialize and Deserialize the JSON string data. In my current scenario, I am getting below format string from my web-service which returns JSON type.
I have got a method in my C# code which calls a web-service method, which returns the string JSON type data. See below example.
string userDetails = myWebService.GetMember(username, Password, out Result);
so userDetails value is
{"FullName":"Manoj Singh","username":"Manoj","Miles":2220,"TierStatus":"Gold","TierMiles":23230,"MilesExpiry":12223,"ExpiryDate":"31 January 2011","PersonID":232323,"AccessToken":"sfs23232s232","ActiveCardNo":"232323223"}
Now I want to write JSONHelper Class in which there will be methods to Serialize and Deserialize the string type of JSON, and will return the dictionary type of values.
Have you looked at http://json.codeplex.com/ ?
I've used it and find json.net very good. Not sure why you'd want to write your own.
You can use the JavaScriptSerializer class in the System.Web.Script.Serialization namespace:
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
object result = jsonSerializer.DeserializeObject(jsonString);
Assuming your jsonString represents a object this should return a dictionary. But you will need to check the type carefully as there is no guarantee it won't return an IEnumerable for example if you give it a json list.
Better still you can use a strongly type deserialization:
http://pietschsoft.com/post/2008/02/NET-35-JSON-Serialization-using-the-DataContractJsonSerializer.aspx
If you know the return signature of your web method this is a far better solution.
Related
I am using C# and trying to generate a JSON string from a dynamic object.
dynamic reply = new System.Dynamic.ExpandoObject();
reply.name = "John";
reply.wins = 42;
string json = System.Web.Helpers.Json.Encode(reply);
System.Console.WriteLine(json);
(Note, the above requires a reference to the System.Web.Helpers assembly.)
I was hoping for this to output the string:
{"name":"John","wins":42}
But it actually outputs:
[{"Key":"name","Value":"John"},{"Key":"wins","Value":42}]
What do I need to change to get the output I was hoping for?
Just download the Newtonsoft.Json Nuget package.
That's the preferred way of working with json in c#.
Your code using Newtonsoft would be:
dynamic reply = new System.Dynamic.ExpandoObject();
reply.name = "John";
reply.wins = 42;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(reply);
System.Console.WriteLine(json);
EDIT:
I just want to explain better why you're getting that result when you're using the System.Web.Helpers.Json.Encode method.
An ExpandoObject is an object which fields are defined at runtime, different than a regular object which fields/properties/methods .. are defined at compile-time. To be able to define them at run-time the expando object internally holds a dictionary, which is a collection of key-value pairs.
I don't know how that helper works but it's probably just a simple serializer and that's why it's serializing to an array of key- value pairs instead of the actual object you're expecting. The library Newtonsoft.Json is almost an standard for c# projects and obviously is aware of how the Expando Object works internally.
Using the Newtonsoft.Json tools:
using Newtonsoft.Json;
/// skip a bunch of other implementation details.
var json = Newtonsoft.Json.JsonConvert.SerializeObject(reply);
That's how I do it.
I'm trying to deserialize my JSON Array using Newtonsoft JSON.NET nugget:
Here's the code:
private List<TemplateTypesObj> getTemplateTypes(JArray array)
{
List<TemplateTypesObj> templateTypes = Newtonsoft.Json.JsonConvert.DeserializeObject<List<TemplateTypesObj>>(array);
return templateTypes;
}
The only issue is that DeserializeObject takes String, not an JArray object. I can do array.toString() but I'm not sure if that is a proper way to do that.
That's because a JArray doesn't really need deserializing. It's not a string/binary representation of an object (which is something you'd deserialize). It's already an object which represents your JSON. You can use it like an object - iterate through it, extract individual items from it.
Check out the docs at http://www.newtonsoft.com/json/help/html/t_newtonsoft_json_linq_jarray.htm - there are methods in there which I'm sure could be used to achieve the conversion you want.
A Chat Room sample program created with NodeJs.
Node.js server will response 3 different format of Json.
I have created a Winform program to accept Json from Websocket.
I use Json.NET JsonMessage jsonResponse =
JsonConvert.DeserializeObject(e.Message.ToString());
to deSerialize one format of Node.js
How to identify different format of Json when serialized?
three type of Json Format
color : "{\"type\":\"color\",\"data\":\"blue\"}"
message : "{\"type\":\"message\",\"action\":\"Change Color\"}"
history : "{\"type\":\"history\",\"data\":[{\"time\":1384825833181,\"text\":\"this is test\",\"author\":\"Tom\",\"color\":\"green\"},{\"time\":1384842730192,\"text\":\"WinForm Send\",\"author\":\"WinForm Say Hello!\",\"color\":\"orange\"},{\"time\":1384842808185,\"text\":\"WinForm Send Again!!!\",\"author\":\"WinForm Say Hello!\",\"color\":\"red\"},{\"time\":1384843229766,\"text\":\"I am fine\",\"author\":\"who are you\",\"color\":\"red\"}]}"
All of the 3 Json formats can create 3 different Class with JsonProperty to map them.
I can verify string with the first few characters.
Are there any other solutions?
I found the following solution could help.
Use JsonCreationConverter . How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?
Use JavaScriptSerializer with dynamic type
Parse json string using JSON.NET
var jss = new JavaScriptSerializer();
dynamic data = jss.Deserialize<dynamic>(e.Message.ToString());
Use JObject.Parse with dynamic type
Deserialize json object into dynamic object using Json.net
Serialized data is as string so, its just a string. As you have also told that you want to identify JSON format. So, better is first convert to JSON & then identify the JSON data type and based on the type call the process or method to process that data.
I'm working with the mvc 4 web api to build a service layer that will always return JSON.
My api method calls actually call another service which returns a JSON object. I then want to just pass this JSON object back as my return object, but I'm not sure what return type to use.
If I use string, it wraps the JSON object in quotes.
By the way, I already changed the default MediaTypeFormatter to be JSON.
Here is an example of the JSON object:
{
"responseHeader":{
"status":0,
"QTime":0,
"params":{
"indent":"on",
"q":"id:100001",
"wt":"json"}},
"response":{"numFound":1,"start":0,"docs":[
{
"Header":"Test Header",
"MaxPrice":515.0,
"ApartmentName":"Apartment 1",
"MaxBathrooms":4.0,
"Pool":true,
"MinBathrooms":2.0,
"MaxBedrooms":4,
"CoveredParking":false}]
}}
In the Beta release, you can use JsonValue (from the System.Json namespace). If your call to the other service returns a string which contains the JSON data, then you can call JsonValue.Parse to load that into the object to return.
In the RC release (or in the current bits from http://aspnetwebstack.codeplex.com) you can use the JToken object (from the Newtonsoft.Json.Linq namespace) - the default JSON serializer and JSON DOM are now coming from the JSON.NET library.
So, the issue turned out to be that I was taking a serialized json object and then reserializing in the JavaScriptSerializerFormatter that overrides the default xml MediaTypeFormatter.
I fixed the issue by returning the JsonValue and then checking the type and not reserializing it.
Thanks carlosfigueira for the help finding this.
To return Json from MVC, use JsonResult. You can first convert the string to an object using DataContractJsonSerializer.
http://shashankshetty.wordpress.com/2009/03/04/using-jsonresult-with-jquery-in-aspnet-mvc/
I have a JSON String returned by my SOAP web service in .NET. It is as follows:
{
"checkrecord":
[
{
"rollno":"abc2",
"percentage":40,
"attended":12,
"missed":34
}
],
"Table1":[]
}
Now I want to parse this string to a JSON Object. I also read this where they have used this line of code:
JObject jsonObj = JObject.Parse(json);
So can I do the same by replacing "json" with my string name. Also do I need to reference any other dll except the NewtonSoft.dll ?
BTW, Here is the full webservice code
use new JavaScriptSerializer().Deserialize<object>(jsonString)
You need System.Web.Extensions dll and import the following namespace.
Namespace: System.Web.Script.Serialization
for more info MSDN
I see that this question is very old, but this is the solution I used for the same problem, and it seems to require a bit less code than the others.
As #Maloric mentioned in his answer to this question:
var jo = JObject.Parse(myJsonString);
To use JObject, you need the following in your class file
using Newtonsoft.Json.Linq;
Another choice besides JObject is System.Json.JsonValue for Weak-Typed JSON object.
It also has a JsonValue blob = JsonValue.Parse(json); you can use. The blob will most likely be of type JsonObject which is derived from JsonValue, but could be JsonArray. Check the blob.JsonType if you need to know.
And to answer you question, YES, you may replace json with the name of your actual variable that holds the JSON string. ;-D
There is a System.Json.dll you should add to your project References.
-Jesse
Since you mentioned that you are using Newtonsoft.dll you can convert a JSON string to an object by using its facilities:
MyClass myClass = JsonConvert.DeserializeObject<MyClass>(your_json_string);
[Serializable]
public class MyClass
{
public string myVar {get; set;}
etc.
}