JSON files read into memory are strings..NET operations on JSON are JSON strings generated and parsed.
There are several common ways to manipulate JSON:
-
Original: Parse as JSON string itself.
-
General pattern painted painted painted painted [u] : this way is to use open source libraries Newtonsoft. Json download address (http://json.codeplex.com/). Add a DLL reference after downloading it.
First add a reference: using newtonsoft.json;
Added: Local DLL download: newtonsoft.json. rar Reference: using newtonsoft.json;
1.Json string common 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 ways of writing:
int retCode = -1; // Return code, 0 indicates success, other indicates failure stringreturnMessage = 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(); }}Copy the code
Parse 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];
}
Copy the code
Json returns the following data:
{"Pictures": [{"PictureSrc":"http://i.ssimg.cn/ssupload/2016/10/17/707f464645f44b4cb9882b75d23ed8f9.png"."PictureLink":""."PictureAlt":"Optical cable 36.50%"."PictureTitle":"Real game championship studio."."PictureTitleLink":"132"."PictureSummary":"Lotus Moonlight studio by mustang and Lotus Moonlight husband and wife live studio, Mustang to short - term stocks, Lotus Moonlight to the main line stocks, good at catching the daily limit and double ox."."OrderTime":"The 2016-10-17 13:16:04"},
{"PictureSrc":"http://i.ssimg.cn/ssupload/2016/10/17/4c38b0a2604e49beaf1e4f7885e6a1a4.png"."PictureLink":""."PictureAlt":"Skyrim shares 6.38%"."PictureTitle":"Securities star of the Day."."PictureTitleLink":"1716"."PictureSummary":"He has been in the stock market for several years and has more than 10 years of actual combat experience. 2014 Securities Star broadcast master annual champion, major first-line websites famous blog, many times interviewed by TV stations.."OrderTime":"The 2016-10-17 13:12:34"}}]Copy the code
Parse to a list of custom entity classes:
Region Retrieves the manual listPublic static List<Pictures> 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 itemin data)
{
Pictures p = new Pictures();
if(! string.IsNullOrEmpty(item["PictureSrc"].ToString()))
{
p.PictureSrc = item["PictureSrc"].ToString(); } list.Add(p); }}return list;
}
#endregion
Copy the code
Pictures entity class definition:
JSON generated entity class tool: Go to >>
Reference: serialize JSON-newtonsoft.json
Parsing JsonArrayList
Convert json format to C# class
2. Parse the nested format of Json strings
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();
Copy the code
3. Parse the Json string array format
string jsonArrayText = "[{'a':'a1','b':'b1'},{'a':'a2','b':'b2'}]"; //"[{' a ':' a1 ', 'b' : 'b1}] even if there is only one element, also need to add a string [] jsonArrayText ="[{\"a\":\"a1\",\"b\":\"b1\"},{\"a\":\"a2\",\"b\":\"b2\"}]"; / / the above writing, as well as the effect of writing JArray JArray = (JArray) JsonConvert. DeserializeObject (jsonArrayText); //jsonArrayText must be an array format string with [] string STR = jArray[0]["a"].ToString();
Copy the code
- Built-in mode: use. 3.5/4.0 of the.net Framework provided by the System. Web. Script. The Serialization namespace JavaScriptSerializer class object Serialization and deserialization, very direct.
Project p1 = new Project() { Input = "stone", Output = "gold"}; JavaScriptSerializer serializer = new JavaScriptSerializer(); string jsonStr = serializer.Serialize(p1); // Serialize: object =>JSON string Response.write (jsonStr); Project p2 = serializer.Deserialize<Project>(jsonStr); // Deserialize: JSON string => object Response.write (p1.input +"= >" + p2.Output);
Copy the code
Note: If VS2010 is used, the Target Framework of the current project is required to be changed. Net Framework 4, cannot use Client Profile. Of course, this System. Web. Extensions. DLL is mainly used in Web, directly in the Console project using feel a little waste of resources. Also, as you can see from the last sentence, serialization and deserialization are a typical implementation of deep copy.