JSONStrToList、StrTosJSON
JSONStrToList
public class Obj { public string Name { get; set; } public double Price { get; set; } }
//json转对象、数组, 反序列化 public static void JSONStringToList() { //json格式字符串 string JsonStr = "{Name:'苹果',Price:5.5}"; JavaScriptSerializer Serializer = new JavaScriptSerializer(); //json字符串转为对象, 反序列化 Obj obj = Serializer.Deserialize<Obj>(JsonStr); Console.Write(obj.Name + ":" + obj.Price + " "); //json格式字符串 string JsonStrs = "[{Name:'苹果',Price:5.5},{Name:'橘子',Price:2.5},{Name:'柿子',Price:16}]"; JavaScriptSerializer Serializers = new JavaScriptSerializer(); //json字符串转为数组对象, 反序列化 List<Obj> objs = Serializers.Deserialize<List<Obj>>(JsonStrs); foreach (var item in objs) { Console.Write(item.Name + ":" + item.Price + " "); } }
StrTosJSON
public static JObject strToJson(string jsonText) { jsonText = "{"shenzheng":"深圳","beijing":"北京","shanghai":[{"zj1":"zj11","zj2":"zj22"},"zjs"]}"; JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText); //或者 //JObject jo = JObject.Parse(jsonText); string zone = jo["shenzheng"].ToString();//输出 "深圳" string zone_en = jo["shanghai"].ToString();//输出 "[{"zj1":"zj11","zj2":"zj22"},"zjs"]" string zj1 = jo["shanghai"][1].ToString();//输出 "zjs" Console.WriteLine(jo); return jo; }