C # Parsing JSON string summary

Source: Internet
Author: User
Tags object serialization

The JSON file is read into memory as a string. NET operation JSON is the generation and parsing of JSON strings.

There are usually several ways to manipulate JSON:

1. Original method : Parse by JSON string itself.

2. Generic mode "★★★★★": This is the way to use the Open Source class library Newtonsoft.json (http://json.codeplex.com/). Add DLL references after download to use.

First Add Reference: Using Newtonsoft.json;

Added: Local DLL Download: Newtonsoft.Json.rar reference: Using Newtonsoft.json;

1.Json string Normal format parsing (common)

String jsontext = "{\" zone\ ": \" Haidian \ ", \" zone_en\ ": \" haidian\ "}"; Jobject Jo = (jobject) jsonconvert.deserializeobject (jsontext); string zone = jo["zone"]. ToString (); string zone_en = jo["Zone_en"]. ToString ();

Other wording:

   int retCode = -1;//return code, 0 indicates success, other indicates failure            string returnmessage = string. empty;//return message, description of the return code            string jsonstr = "{\" retcode\ ": 3,\" returnmessage\ ": \" test message \ "}";            Javascriptobject jsonobj = javascriptconvert.deserializeobject<javascriptobject> (JSONSTR);            if (jsonobj! = null)            {                if (Jsonobj.containskey ("RetCode") && jsonobj["RetCode"]! = null)                {                    int . TryParse (jsonobj["RetCode"). ToString (), out retCode);                }                if (Jsonobj.containskey ("ReturnMessage") && jsonobj["ReturnMessage"]! = null)                {                    ReturnMessage = jsonobj["ReturnMessage"]. ToString ();                }            }

Parsing JOSN list data:

public static Jarray getdata2jarray (string url, string key) {    string jsondata = Httphelper.httpget (URL, "", "gb2312");     Jobject obj = Jobject.parse (jsondata);    Return (Jarray) Obj[key];}

The data returned by the JSON above:

{"Pictures": [{"PICTURESRC": "Http://i.ssimg.cn/ssupload/2016/10/17/707f464645f44b4cb9882b75d23ed8f9.png", " Picturelink ":", "Picturealt": "Light cable 36.50%", "Picturetitle": "Real-game champion Live Room", "Picturetitlelink": "", "picturesummary": "Lotus Pond Moonlight Live Room is by the wild Horse and Lotus Pond Moonlight couple live Live room, Mustang to short-term shares mainly, Lotus Pond moonlight to midline shares mainly, good at grasping trading board and double cattle shares." "," Ordertime ":" 2016-10-17 13:16:04 "},{" picturesrc ":" http://i.ssimg.cn/ssupload/2016/10/17/ 4c38b0a2604e49beaf1e4f7885e6a1a4.png "," Picturelink ":" "," Picturealt ":" Skyline shares 6.38% "," Picturetitle ":" The strongest ace of securities star "," Picturetitlelink ":" 1716 "," picturesummary ":" Deep into the sea for several years, with more than 10 years of actual combat experience. " 2014 Securities star of the year champion, the major first-line website famous blog, many times to accept television interview. "," Ordertime ":" 2016-10-17 13:12:34 "}]}

Resolves to a list of custom entity classes:

#region Get hand-made list//<summary>///get hand-compiled list///</summary>///<returns></returns>public static list <Pictures> gethandwritelist () {    list<pictures> List = new list<pictures> ();    var data = Common.LiveCastUserManageAPI.GetData2JArray (Cmsapisite, "Pictures");    if (data! = NULL && data. Count > 0)    {        foreach (var item in data)        {            Pictures p = new Pictures ();            if (!string. IsNullOrEmpty (item["Picturesrc"). ToString ()))            {                p.picturesrc = item["Picturesrc"]. ToString ();            }            List. ADD (P);        }    }    return list;} #endregion
Pictures definition of entity class:
     Public classPictures {/// <summary>        /// http://i.ssimg.cn/ssupload/2016/10/17/e6500633d4cb4a918c8f45e2c71ab8f6.jpg        /// </summary>         Public stringPICTURESRC {Get;Set; } /// <summary>        ///         /// </summary>         Public stringPicturelink {Get;Set; } /// <summary>        ///Sino-color shares 53%/// </summary>         Public stringPicturealt {Get;Set; } /// <summary>        ///where are the double bull stocks in the four quarter? /// </summary>         Public stringPicturetitle {Get;Set; } /// <summary>        ///Meihaoxiangwang/// </summary>         Public stringPicturetitlelink {Get;Set; } /// <summary>        ///Lotus Pond Moonlight Live Room is by the wild Horse and Lotus Pond Moonlight couple live Live room, Mustang to short-term shares mainly, Lotus Pond moonlight to Middle-line shares mainly, good at grasping trading board and double cattle stocks. /// </summary>         Public stringpicturesummary {Get;Set; } /// <summary>        ///Stock name/// </summary>         Public stringStockName {Get;Set; } /// <summary>        ///Stock return rate/// </summary>         Public stringRate {Get;Set; } /// <summary>        ///Nickname/// </summary>         Public stringNickname {Get;Set; } /// <summary>        ///Avatar/// </summary>         Public stringheadimg {Get;Set; } /// <summary>        ///name of the live room/// </summary>         Public stringCastroomname {Get;Set; } }
View Code

JSON generated entity class tool: Click >>

Reference: Serialization Json-newtonsoft.json

Parsing jsonarraylist

Convert JSON format to C # class

2.Json String Nesting format parsing

String jsontext = "{\" beijing\ ": {\" zone\ ": \" Haidian \ ", \" zone_en\ ": \" haidian\ "}}"; Jobject Jo = (jobject) jsonconvert.deserializeobject (jsontext), String zone = jo["Beijing" ["zone"]. ToString (); string zone_en = jo["Beijing" ["Zone_en"]. ToString ();

3.Json string Array Format parsing

String Jsonarraytext = "[{' A ': ' A1 ', ' B ': ' B1 '},{' a ': ' A2 ', ' B ': ' B2 '}]"; "[{' A ': ' A1 ', ' B ': ' B1 '}] even if there is only one element, you need to add []string jsonarraytext =" [{\ "a\": \ "a1\", \ "b\": \ "b1\"},{\ "a\": \ "a2\", \ "B\" : \ "B2\"}] ";  The above notation is the same as the effect jarray Jarray = (jarray) jsonconvert.deserializeobject (jsonarraytext);//jsonarraytext must be a band [] Array format Strings String str = jarray[0]["a"]. ToString ();

3. Built-in mode : Using the. NET Framework 3.5/ The JavaScriptSerializer class in the System.Web.Script.Serialization namespace provided in 4.0 is a straightforward object serialization and deserialization.

Project P1 = new Project () {Input = "stone", Output = "Gold"}; JavaScriptSerializer serializer = new JavaScriptSerializer (); string jsonstr = serializer. Serialize (p1);  Serialization: Object =>json String Response.Write (JSONSTR); Project P2 = serializer. Deserialize<project> (JSONSTR); Deserialization: JSON string = = Object Response.Write (p1. Input + "=" + P2. Output);

Note: If you are using VS2010, you are required to change the Target Framework of the current project to. Net Framework 4, and you cannot use client profile. Of course, this System.Web.Extensions.dll is mainly used by the Web, directly in the console project with a feeling a little waste of resources.
In addition, it can be seen from the last sentence that serialization and deserialization are typical implementations of deep copies .

C # Parsing JSON string summary

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.