C # are two ways to parse the json

 

 

C # convert Json in the ways to use!

This introduces 2,4. The third method more limited use, so I do not have in-depth study.

The second method

  I use more ways, this method is the built-in .NET, more convenient to use

A, using json serializer obtain generic objects

Using Dictionary <string, object> object conversion receiver json finished, and the desired object can be extracted with json generic query command.

string JsonData = “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”;
JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<string,object> json = (Dictionary<string, object>)serializer.DeserializeObject(JsonData);
string firstKey = json.ElementAt(0).Key;
string secondKey = json.ElementAt(1).Key;

Of course there are many other data types, so be flexible use conversion.

object[] jsonInnerObj = (object[])serializer.DeserializeObject(jsonList);
// mandatory conversion
Dictionary<string, object> jsonLast = (Dictionary<string, object>)jsonInnerObj[i]; 

B, using the object class to receive json

public class Info
    {
        public List <TitleProperty> Title {get; set;} // the name of the attribute, and must be the same json format string "key" value.
        public string PreSum { get; set; }
        public List <CalculateFeature> CalculateSum {get; set;} // Array Processing
        public string [] Float {get; set;} // Array Processing
        public List <RowCells> TableCell; // generic process   
    }

Depending on the format json object, create a class. It should be noted, the difference between the array and the generic array is [123,123,123] type of data, and is a generic [{ "a": "a", "b": "b"}, { "a ":" a "," b ":" b "}, {" a ":" a "," b ":" data b "}] type.

If you continue to read generics, we also need to create a class for which the corresponding data again.

After use in the control page

string json = form["TextArea1"];
JavaScriptSerializer js = new JavaScriptSerializer (); // instantiate a class can be serialized data
Info list = js.Deserialize <Info> (json); // json data into the object type and assigned to the list
List<TitleProperty> title = list.Title;
string preSum = list.PreSum ;
List<CalculateFeature> calculateSum=list.CalculateSum;
string[] Float = list.Float;
List<RowCells> tableList = list.TableCell;

C, deserialization

De-serialization is relatively simple, if it is generic, then the corresponding generic can then be deposited directly into a key, c # will Autosave is json format.

return Json(new { TotalItem = totalItem, Page = page, TotalPage = pageCountInt, List = _viewModel.InfoListVM }, JsonRequestBehavior.AllowGet);

The fourth method, more versatile, and can use linq, so more recommended!

4.1 Class Library Newtonsoft.Json (Download http://json.codeplex.com/). After downloading the project will be able to join with.

Generally used JObject, JsonReader, JsonWriter process. In this way the most versatile and flexible and can be modified at any time.

4.2 Details

4.2.0 Adding namespace: using Newtonsoft.Json;

4.2.1 Use JsonReader read Json string

string jsonText = @"{""input"" : ""value"", ""output"" : ""result""}";
JsonReader reader = new JsonTextReader(new StringReader(jsonText));
while (reader.Read())
{
Console.WriteLine(reader.TokenType + "\t\t" + reader.ValueType + "\t\t" + reader.Value+"\r\n");
}
Console.ReadKey(); 

4.2.2 Use JsonWriter write string

StringWriter sw = new StringWriter();
JsonWriter writer = new JsonTextWriter(sw);
writer.WriteStartObject();
writer.WritePropertyName("input");
writer.WriteValue("value");
writer.WritePropertyName("output");
writer.WriteValue("result");
writer.WriteEndObject();
writer.Flush();
string jsonText2 = sw.GetStringBuilder().ToString();
Console.WriteLine(jsonText2);
Console.ReadKey();

4.2.3 string read JObject

4.2.3.1 add a namespace: using Newtonsoft.Json.Linq;

JObject jo = JObject.Parse(jsonText);
string[] values = jo.Properties().Select(item => item.Value.ToString()).ToArray();
4.2.4 Object JsonSerializer reader (based JsonWriter and JsonReader)
4.2.4.1 Array Data
string jsonArrayText1 = "[{'a':'a1','b':'b1'},{'a':'a2','b':'b2'}]";
JArray ja = (JArray)JsonConvert.DeserializeObject(jsonArrayText1);
string ja1a = ja[1]["a"].ToString();
//or
JObject o = (JObject)ja[1];
string oa = o["a"].ToString();

4.2.4.2 Nested format

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

4.2.4.3 Custom use

1. Auxiliary Class

class Project
{
public string Input { get; set; }
public string Output { get; set; }
}

2. Use

            Project p = new Project() { Input = "stone", Output = "gold" };
            JsonSerializer serializer = new JsonSerializer();
            StringWriter sw1 = new StringWriter();
            serializer.Serialize(new JsonTextWriter(sw), p);
            Console.WriteLine(sw.GetStringBuilder().ToString());
            StringReader sr = new StringReader(@"{""Input"":""stone"", ""Output"":""gold""}");
            Project p1 = (Project)serializer.Deserialize(new JsonTextReader(sr), typeof(Project));
            Console.WriteLine(p1.Input + "=>" + p1.Output);
            Console.ReadKey();

About Newtonsoft.Json Advanced Usage  http://www.cnblogs.com/yanweidie/p/4605212.html

C # convert Json in the ways to use!

This introduces 2,4. The third method more limited use, so I do not have in-depth study.

The second method

  I use more ways, this method is the built-in .NET, more convenient to use

A, using json serializer obtain generic objects

Using Dictionary <string, object> object conversion receiver json finished, and the desired object can be extracted with json generic query command.

string JsonData = “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”;
JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<string,object> json = (Dictionary<string, object>)serializer.DeserializeObject(JsonData);
string firstKey = json.ElementAt(0).Key;
string secondKey = json.ElementAt(1).Key;

Of course there are many other data types, so be flexible use conversion.

object[] jsonInnerObj = (object[])serializer.DeserializeObject(jsonList);
// mandatory conversion
Dictionary<string, object> jsonLast = (Dictionary<string, object>)jsonInnerObj[i]; 

B, using the object class to receive json

public class Info
    {
        public List <TitleProperty> Title {get; set;} // the name of the attribute, and must be the same json format string "key" value.
        public string PreSum { get; set; }
        public List <CalculateFeature> CalculateSum {get; set;} // Array Processing
        public string [] Float {get; set;} // Array Processing
        public List <RowCells> TableCell; // generic process   
    }

Depending on the format json object, create a class. It should be noted, the difference between the array and the generic array is [123,123,123] type of data, and is a generic [{ "a": "a", "b": "b"}, { "a ":" a "," b ":" b "}, {" a ":" a "," b ":" data b "}] type.

If you continue to read generics, we also need to create a class for which the corresponding data again.

After use in the control page

string json = form["TextArea1"];
JavaScriptSerializer js = new JavaScriptSerializer (); // instantiate a class can be serialized data
Info list = js.Deserialize <Info> (json); // json data into the object type and assigned to the list
List<TitleProperty> title = list.Title;
string preSum = list.PreSum ;
List<CalculateFeature> calculateSum=list.CalculateSum;
string[] Float = list.Float;
List<RowCells> tableList = list.TableCell;

C, deserialization

De-serialization is relatively simple, if it is generic, then the corresponding generic can then be deposited directly into a key, c # will Autosave is json format.

return Json(new { TotalItem = totalItem, Page = page, TotalPage = pageCountInt, List = _viewModel.InfoListVM }, JsonRequestBehavior.AllowGet);

The fourth method, more versatile, and can use linq, so more recommended!

4.1 Class Library Newtonsoft.Json (Download http://json.codeplex.com/). After downloading the project will be able to join with.

Generally used JObject, JsonReader, JsonWriter process. In this way the most versatile and flexible and can be modified at any time.

4.2 Details

4.2.0 Adding namespace: using Newtonsoft.Json;

4.2.1 Use JsonReader read Json string

string jsonText = @"{""input"" : ""value"", ""output"" : ""result""}";
JsonReader reader = new JsonTextReader(new StringReader(jsonText));
while (reader.Read())
{
Console.WriteLine(reader.TokenType + "\t\t" + reader.ValueType + "\t\t" + reader.Value+"\r\n");
}
Console.ReadKey(); 

4.2.2 Use JsonWriter write string

StringWriter sw = new StringWriter();
JsonWriter writer = new JsonTextWriter(sw);
writer.WriteStartObject();
writer.WritePropertyName("input");
writer.WriteValue("value");
writer.WritePropertyName("output");
writer.WriteValue("result");
writer.WriteEndObject();
writer.Flush();
string jsonText2 = sw.GetStringBuilder().ToString();
Console.WriteLine(jsonText2);
Console.ReadKey();

4.2.3 string read JObject

4.2.3.1 add a namespace: using Newtonsoft.Json.Linq;

JObject jo = JObject.Parse(jsonText);
string[] values = jo.Properties().Select(item => item.Value.ToString()).ToArray();
4.2.4 Object JsonSerializer reader (based JsonWriter and JsonReader)
4.2.4.1 Array Data
string jsonArrayText1 = "[{'a':'a1','b':'b1'},{'a':'a2','b':'b2'}]";
JArray ja = (JArray)JsonConvert.DeserializeObject(jsonArrayText1);
string ja1a = ja[1]["a"].ToString();
//or
JObject o = (JObject)ja[1];
string oa = o["a"].ToString();

4.2.4.2 Nested format

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

4.2.4.3 Custom use

1. Auxiliary Class

class Project
{
public string Input { get; set; }
public string Output { get; set; }
}

2. Use

            Project p = new Project() { Input = "stone", Output = "gold" };
            JsonSerializer serializer = new JsonSerializer();
            StringWriter sw1 = new StringWriter();
            serializer.Serialize(new JsonTextWriter(sw), p);
            Console.WriteLine(sw.GetStringBuilder().ToString());
            StringReader sr = new StringReader(@"{""Input"":""stone"", ""Output"":""gold""}");
            Project p1 = (Project)serializer.Deserialize(new JsonTextReader(sr), typeof(Project));
            Console.WriteLine(p1.Input + "=>" + p1.Output);
            Console.ReadKey();

About Newtonsoft.Json Advanced Usage  http://www.cnblogs.com/yanweidie/p/4605212.html

Guess you like

Origin www.cnblogs.com/cfas/p/11080203.html