Several ways to parse JSON in C #

Source: Internet
Author: User
Tags silverlight

To become a master of the sea, you must know the true name of every drop of water in the sea.

At first I just wanted to find a way to convert the JSON array, which turned out to be a bunch of MSDN.

The search process inevitably comes across a whole bunch of nouns: WCF = DataContract = DataMember = DataContractJsonSerializer, and then the namespace is constantly introduced.

This experience immediately reminds me of the words of a sorcerer in a novel that is quoted above. Static language is a bit of a freak-out, ready to go, and then it's possible to start working.

Contrast
. Several common parsing JSON methods under net
Main class name Space Limit built-in LINQ support
DataContractJsonSerializer System.Runtime.Serialization.Json General Whether
JavaScriptSerializer System.Web.Script.Serialization Can only be used in a Web environment Whether
Jsonarray, Jsonobject, Jsonvalue System.json Can only be used in Silverlight Is
JsonConvert, Jarray, Jobject, Jvalue, Jproperty Newtonsoft.json General Is

Preparing data

Entity class:

[DataContract]PublicClass Person {[DataMember (Order =0, isrequired =true)] public string Name { get; set;} [DataMember (Order = 1)] public int Age { get; set;} [DataMember (Order = 2)] public bool Alive { get; set;} [DataMember (Order = 3)] public string[] Favoritefilms { get; set;} [DataMember (Order = 4)] public person child { get; set;} } 

Defined:

Action<object> log = o => Console.WriteLine(o);Func<int, int, int> add = (x, y) => x + y;var p1 = new Person { Age = 12, Alive = true, Name = "lj", FavoriteFilms = new[] { "Up", "Avatar" }};var p2 = new Person() { Age = 28, Name = "cy", Child = p1 }; 
Using DataContractJsonSerializer

Help class:

  Using System.Runtime.Serialization.Json;///<summary>Parsing json, imitation JavaScript style///</summary>PublicStaticclass JSON {public static T parse<t> (string jsonstring) {using (var ms = new memorystream (Encoding.UTF8.GetBytes (jsonstring))) {return (T) new datacontractjsonserializer ( typeof (T)). ReadObject (MS); }} public static string stringify (object jsonobject) {using (var ms = new MemoryStream ()) {new datacontractjsonserializer (Jsonobject.gettype ()). WriteObject (MS, Jsonobject); return Encoding.UTF8.GetString (Ms. ToArray ()); } } } 

Usage:

    // 序列化    var jsonString = JSON.stringify(new[] { p1, p2 });    log(jsonString == JSON.stringify(new List<Person>() { p1, p2 }));   //true    log(jsonString);    // 反序列化,泛型集合    JSON.parse<List<Person>>(jsonString);    // 数组转换                JSON.parse<Person[]>(jsonString);

Output:

[{"Name":"LJ,""Age":12, "Alive": true, " Favoritefilms ": [" Avatar "]," child ": null},{ "Name":  "Cy",  "Age": 28, "Alive": false, Favoritefilms ": null," Age ": 12,true ,  "Favoritefilms": [ "Up",  "child": null}]           
Using JavaScriptSerializer
  // using System.Web.Script.Serialization;        var jser    = new JavaScriptSerializer();    var json    = jser.Serialize(new List<Person>() { p1, p2 }); var persons = jser.Deserialize<List<Person>>(json);
Using Silverlight
  Using System.jsonvar css ="{\" #header \ ": {background:\" red\ "}, Layout: [5,4,1],color:\" cyan\ "}";var style = Jsonobject.parse (CSS)As Jsonobject; (from SIn stylewhere s.key =  "color" select ( string) s.value). First (). ToString (); //"cyan" //more operations Style[ "layout" [ 0] = 22; var HD = Style[ "#header"]; Style[ "body>div+p"] = hd Style. Remove ( "#header"); var bd = new jsonobject (); Bd[ "border"] =  "1px solid cyan"; Style[ "body>div+p"][ "#meta"] = BD; style. ToString (); //{"Layout": [22,4,1], "color": "Cyan", "body>div+p": {"background": "Red", "#meta": {"border ":" 1px solid Cyan "}}}              
Using Json.NET
  // using Newtonsoft.Json;        var json = JsonConvert.SerializeObject(new[] { p1, p2 });    var persons = JsonConvert.DeserializeObject<List<Person>>(json); var ja = JArray.Parse(jsonString); log(ja);//注意,格式化过的输出

Output:

[  {"Name":"LJ,""Age":12,"Alive":true, "Favoritefilms": [ "Up", "Avatar"], "child": null}, { "Name": "Cy", "age": 
                  
                   28, 
                   "Alive": false, "Favoritefilms": null, "child": { "Name": "LJ", "age":  "Alive": True, "Favoritefilms": [ "Up", "Avatar"], "Child ": null}}] /c24> 
                  

Linq:

    var ageCount = ja.Select(j => (int)j["Age"]).Aggregate(add);        var q = from j in ja where !j["Name"].Value<string>().Equals("lj") select (int)j["Age"]; log(q.Aggregate(add) == ageCount); //false

Other:

  Nested constructors that resemble LINQ to XML:var Jo =New Jobject (New Jproperty ("Age", persons. Select (P = p.age)),New Jproperty ("Funny",True),New Jproperty (new jarray (new[] { 2, 4, 1})); Log (Jo); //jobject operation var css = var style = Jobject.parse (CSS); var bd = new jobject (); Bd[ "color"] = " 1px solid cyan "; Style[ "border"] = BD; var HD = Style[ "#header"]; Style[ "body>div+p"] = hd Hd.parent.remove (); Style[ "layout"][0] = 22; log (style);                

Output:

    {      "age": [        12,        28      ],      "funny": true, "array": [ 2, 4, 1 ] } { "layout": [ 22, 4, 1 ], "border": { "color": "1px solid cyan" }, "body>div+p": { "background": "red" } }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.