Parse JSON String to JSON Object in C#.NET - c#

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.
}

Related

Extract data from Json with json.net

so I have a JSON text and I need to Extract Value of some fields from it
{"data":{"shortcode":{"id":"id123","shortcode":"alpha1","by":{"page_info":{"has_next_page":true,"cursor":"sometext=="},"edges":[{"node":{"id":"id1234","username":"admin123","full_name":"admin name",}},{"node":{"id":"id4321","username":"user123","full_name":"user ",}}]}}},"status":"ok"}
now I need the value of every single "username" field and "cursor" from it
I'm new to this topic and I appreciate any kind of help
You could install Newtonsoft.Json, as a Nuget package, if you don't already have it installed in your project. Then use JsonConvert.DeserializeObject() method to parse it into a dynamic object type, using which you can access all its fields/properties.
Code would look something like this-
Add referenceto Newtonsoft.Json
using Newtonsoft.Json;
DeserializeObject method to parse a string into dynamic type (dynamic can be used instead of var)
var obj = JsonConvert.DeserializeObject<dynamic>(text);
For cursor field mentioned in your example
Console.WriteLine(obj.data.shortcode.by.page_info.cursor);
Iterate for each username mentioned your example
foreach (var edge in obj.data.shortcode.by.edges)
{
Console.WriteLine(edge.node.id);
}
NOTE- Because you are using a dynamic type, you will have to be sure that you check for null values to avoid any "NullRefereneException".
Well you can make a new class that match the structure of your json then deserialize the json into that class.

Generate JSON string from dynamic ExpandoObject

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.

JavaScriptSerializer: Cannot deserialize JSON that uses # symbol in property name

I am using a 3rd party server that exposes an API via REST(so it is not possible to change the JSON). The JSON it returns is in a format like:
[
{
"#noun":"tag",
"#version":0,
"#tag":"myFoo"
}
]
I created a C# object to represent this item
public class ResponseItem
{
public string noun {get;set;}
.....
}
however, when I try to use the JavaScriptSerializer to deserialize this object, the properties do NOT get assigned. The serializer seems to be unable to handle the properties with the # symbol in front of the name.
Any ideas on how to solve this?
Ok, so after some finagling, I ditched the JavaScriptSerializer. I switched over to the DataContractJsonSerializer. I then use well defined data contracts and use the DataMember attribute to specify the name.
i.e.
[DataContract]
public class ResponseItem
{
[DataMember(Name="#noun")]
public string Noun {get;set;}
....
}
There may be a better/different way, but this works and is an acceptable solution

Json Object Deserialization in c#

im tyring to deserialize my object coming from client side having following format:
{'goalplans':
[{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0}
]}
thing is that im not able to deserialze it on my server side .
Please tell me how can i deserialize the Json object to a list object like
List . i tried many ways but not working.
serialize/deserialize objects to/from JSON exist Since .NET 3.5, try this
using System.Web.Script.Serialization;
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<dynamic>(jsonText);
See here for more details
Hope this helps
One possible third party component is JSON.NET. Personally I have made very good experience with that library ( it is available using nuget for example )
I solved the problem by myself. Simply adding [Serializable] to my class
and changed method to take argument of class type ...
e.g.
//My class
[Serializable]
public class GoalPlanList{}
//method
public static int GoalplanAddUPD(List<GoalPlanList> goalplans)
{
foreach (GoalPlanList goals in goalplans)
{}
}

Looking to create JSON Serializer/Deserializer Class using C# 2.0

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.

Categories