Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON String to JSON Object in C#.NET

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

like image 909
Parth Doshi Avatar asked Nov 28 '11 04:11

Parth Doshi


4 Answers

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

like image 96
Baz1nga Avatar answered Oct 17 '22 12:10

Baz1nga


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;
like image 44
demonicdaron Avatar answered Oct 17 '22 11:10

demonicdaron


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

like image 6
Jesse Chisholm Avatar answered Oct 17 '22 12:10

Jesse Chisholm


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.
}
like image 3
azakgaim Avatar answered Oct 17 '22 13:10

azakgaim