JSON string processing C# parsing JSON string summary serialization Json-Newtonsoft.Json

C# parsing JSON string summary

 

JSON files are read into memory as strings, and .NET to manipulate JSON is to generate and parse JSON strings.

There are usually several ways to manipulate JSON:

1. Original method : parse the JSON string by yourself.

 

2. General method [★★★★★] : This method is to use the open source class library Newtonsoft.Json (download address http://json.codeplex.com/ ). After downloading, add the dll reference and it can be used.

First add the reference: using Newtonsoft.Json;

Added: Local dll download: Newtonsoft.Json.rar    Reference: using Newtonsoft.Json;

 

1. Json string common format parsing (commonly used)

string jsonText = "{\"zone\":\"海淀\",\"zone_en\":\"haidian\"}";
JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);
string zone = jo["zone"].ToString();
string zone_en = jo["zone_en"].ToString();

 

Other ways of writing:

copy code
   int retCode = -1;//Return code, 0 means success, other means failure
            string returnMessage = string.Empty;//Return message, description of return code
            string jsonStr = "{\"RetCode\":3,\"ReturnMessage\":\"测试消息\"}";
            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();
                }
            }
copy code

 

Parse the 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 above Json:

copy code
{"Pictures":
[
{"PictureSrc":"http://i.ssimg.cn/ssupload/2016/10/17/707f464645f44b4cb9882b75d23ed8f9.png","PictureLink":"","PictureAlt":"Clear cable 36.50%"," PictureTitle":"Real match champion live broadcast room","PictureTitleLink":"132","PictureSummary":"The Lotus Pond Moonlight Live Room is a live broadcast room jointly broadcasted by Yema and Lotus Pond Moonlight. Lord, Lotus Pond Moonlight focuses on midline stocks, and is good at catching the daily limit and doubling bull stocks.","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" :"Securities Star's strongest ace broadcaster","PictureTitleLink":"1716","PictureSummary":"In-depth stock market for several years, with more than ten years of practical experience. 2014 Securities Star broadcaster annual champion, major A well-known blog on the first-line website, and has been interviewed by TV stations many times.","OrderTime":"2016-10-17 13:12:34"}
]
}
copy code

Parse into a list of custom entity classes:

copy code
#region Get the handcrafted list
/// <summary>
/// Get the handwritten 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
copy code
Definition of the Pictures entity class:
copy code
    public class Pictures
    {
        /// <summary>
        /// http://i.ssimg.cn/ssupload/2016/10/17/e6500633d4cb4a918c8f45e2c71ab8f6.jpg
        /// </summary>
        public string PictureSrc { get; set; }
        /// <summary>
        ///
        /// </summary>
        public string PictureLink { get; set; }
        /// <summary>
        /// NFC shares 53%
        /// </summary>
        public string PictureAlt { get; set; }
        /// <summary>
        /// Where are the bull stocks that doubled in the fourth quarter?
        /// </summary>
        public string PictureTitle { get; set; }
        /// <summary>
        /// meihaoxiangwang
        /// </summary>
        public string PictureTitleLink { get; set; }
        /// <summary>
        /// Lotus Pond Moonlight Live Streaming Room is a live broadcast studio jointly broadcasted by Yema and Lotus Pond Moonshine. Mustang mainly focuses on short-term stocks, while Hetang Moonshine mainly focuses on mid-line stocks, and is good at catching the daily limit and doubling the bull stocks.
        /// </summary>
        public string PictureSummary { get; set; }

        /// <summary>
        /// stock name
        /// </summary>
        public string StockName { get; set; }

        /// <summary>
        /// stock return
        /// </summary>
        public string Rate { get; set; }

        /// <summary>
        /// Nick name
        /// </summary>
        public string NickName { get; set; }

        /// <summary>
        /// Avatar
        /// </summary>
        public string HeadImg { get; set; }

        /// <summary>
        /// Live room name
        /// </summary>
        public string CastRoomName { get; set; }


    }
copy code

JSON generation entity class tool: click >>

 

Reference: Serializing Json - Newtonsoft.Json

Parse JsonArrayList

Convert json format to C# class

 

2. Json string nested format parsing

string jsonText = "{\"beijing\":{\"zone\":\"海淀\",\"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 writing has the same effect as this writing
JArray jArray = (JArray)JsonConvert.DeserializeObject(jsonArrayText);//jsonArrayText must be an array format string with []
string str = jArray[0]["a"].ToString();

 

3. Built-in method : use the JavaScriptSerializer class under the System.Web.Script.Serialization namespace provided in .NET Framework 3.5/4.0 to serialize and deserialize objects directly.

copy code
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); //Deserialize: JSON string => object
Response.Write(p1.Input + "=>" + p2.Output);
copy code

JSON files are read into memory as strings, and .NET to manipulate JSON is to generate and parse JSON strings.

There are usually several ways to manipulate JSON:

1. Original method : parse the JSON string by yourself.

 

2. General method [★★★★★] : This method is to use the open source class library Newtonsoft.Json (download address http://json.codeplex.com/ ). After downloading, add the dll reference and it can be used.

First add the reference: using Newtonsoft.Json;

Added: Local dll download: Newtonsoft.Json.rar    Reference: using Newtonsoft.Json;

 

1. Json string common format parsing (commonly used)

string jsonText = "{\"zone\":\"海淀\",\"zone_en\":\"haidian\"}";
JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);
string zone = jo["zone"].ToString();
string zone_en = jo["zone_en"].ToString();

 

Other ways of writing:

copy code
   int retCode = -1;//Return code, 0 means success, other means failure
            string returnMessage = string.Empty;//Return message, description of return code
            string jsonStr = "{\"RetCode\":3,\"ReturnMessage\":\"测试消息\"}";
            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();
                }
            }
copy code

 

Parse the 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 above Json:

copy code
{"Pictures":
[
{"PictureSrc":"http://i.ssimg.cn/ssupload/2016/10/17/707f464645f44b4cb9882b75d23ed8f9.png","PictureLink":"","PictureAlt":"Clear cable 36.50%"," PictureTitle":"Real match champion live broadcast room","PictureTitleLink":"132","PictureSummary":"The Lotus Pond Moonlight Live Room is a live broadcast room jointly broadcasted by Yema and Lotus Pond Moonlight. Lord, Lotus Pond Moonlight focuses on midline stocks, and is good at catching the daily limit and doubling bull stocks.","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" :"Securities Star's strongest ace broadcaster","PictureTitleLink":"1716","PictureSummary":"In-depth stock market for several years, with more than ten years of practical experience. 2014 Securities Star broadcaster annual champion, major A well-known blog on the first-line website, and has been interviewed by TV stations many times.","OrderTime":"2016-10-17 13:12:34"}
]
}
copy code

Parse into a list of custom entity classes:

copy code
#region Get the handcrafted list
/// <summary>
/// Get the handwritten 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
copy code
Definition of the Pictures entity class:
copy code
    public class Pictures
    {
        /// <summary>
        /// http://i.ssimg.cn/ssupload/2016/10/17/e6500633d4cb4a918c8f45e2c71ab8f6.jpg
        /// </summary>
        public string PictureSrc { get; set; }
        /// <summary>
        ///
        /// </summary>
        public string PictureLink { get; set; }
        /// <summary>
        /// NFC shares 53%
        /// </summary>
        public string PictureAlt { get; set; }
        /// <summary>
        /// Where are the bull stocks that doubled in the fourth quarter?
        /// </summary>
        public string PictureTitle { get; set; }
        /// <summary>
        /// meihaoxiangwang
        /// </summary>
        public string PictureTitleLink { get; set; }
        /// <summary>
        /// Lotus Pond Moonlight Live Streaming Room is a live broadcast studio jointly broadcasted by Yema and Lotus Pond Moonshine. Mustang mainly focuses on short-term stocks, while Hetang Moonshine mainly focuses on mid-line stocks, and is good at catching the daily limit and doubling the bull stocks.
        /// </summary>
        public string PictureSummary { get; set; }

        /// <summary>
        /// stock name
        /// </summary>
        public string StockName { get; set; }

        /// <summary>
        /// stock return
        /// </summary>
        public string Rate { get; set; }

        /// <summary>
        /// Nick name
        /// </summary>
        public string NickName { get; set; }

        /// <summary>
        /// Avatar
        /// </summary>
        public string HeadImg { get; set; }

        /// <summary>
        /// Live room name
        /// </summary>
        public string CastRoomName { get; set; }


    }
copy code

JSON generation entity class tool: click >>

 

Reference: Serializing Json - Newtonsoft.Json

Parse JsonArrayList

Convert json format to C# class

 

2. Json string nested format parsing

string jsonText = "{\"beijing\":{\"zone\":\"海淀\",\"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 writing has the same effect as this writing
JArray jArray = (JArray)JsonConvert.DeserializeObject(jsonArrayText);//jsonArrayText must be an array format string with []
string str = jArray[0]["a"].ToString();

 

3. Built-in method : use the JavaScriptSerializer class under the System.Web.Script.Serialization namespace provided in .NET Framework 3.5/4.0 to serialize and deserialize objects directly.

copy code
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); //Deserialize: JSON string => object
Response.Write(p1.Input + "=>" + p2.Output);
copy code

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325050086&siteId=291194637