分类:
.Net
//字符串转json public static void strJson() { string jsonText = "{\"shenzheng\":\"深圳\",\"beijing\":\"北京\",\"shanghai\":[{\"zj1\":\"zj11\",\"zj2\":\"zj22\"},\"zjs\"]}"; string jsonText2 = "{\"Specificlocation\":[{\"zj1\":\"zj11\",\"zj2\":\"zj22\"},{\"cq1\":\"cq11\",\"cq2\":\"cq22\"}]}"; string strjson3 = "{ address: \"CN|北京|北京|None|CHINANET|1|None\", content:{ address: \"北京市\", address_detail:{city: \"北京市\", city_code: 131,district: \"\",province: \"北京市\", street: \"\",street_number: \"\" }, point: { x: \"116.39564504\",y: \"39.92998578\"}},status: 0}"; string jsonText4= "{ \"error_response\":{ \"sub_msg\":\"非法参数\", \"code\":50, \"sub_code\":\"isv.invalid-parameter\", \"msg\":\"Remote service error\" } }"; JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText2);//或者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" // string zj1 =jo["Specificlocation"][0]["zj1"].ToString(); //输出 "zj11" //string sub_msg =jo["error_response"]["sub_msg"].ToString() //输出 "非法参数" Console.WriteLine(jo["Specificlocation"].Count()); } //对象与数组转JSON public static void GetJsonString() { //初始化对象 Obj product = new Obj() { Name = "苹果", Price = 5.5 }; //序列化 string o = new JavaScriptSerializer().Serialize(product);//值:"{\"Name\":\"苹果\",\"Price\":5.5}" //数组转json List<Obj> products = new List<Obj>(){ new Obj(){Name="苹果",Price=5.5}, new Obj(){Name="橘子",Price=2.5}, new Obj(){Name="干柿子",Price=16.00} }; //序列化 string os = new JavaScriptSerializer().Serialize(products); //输出 "{\"GetProducts\":[{\"Name\":\"苹果\",\"Price\":5.5},{\"Name\":\"橘子\",\"Price\":2.5},{\"Name\":\"干柿子\",\"Price\":16}]}" Console.WriteLine(os); } //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 + "\r\n"); //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 + "\r\n"); } } public class Obj { public string Name { get; set; } public double Price { get; set; } } static void Main(string [] args) { strJson(); GetJsonString(); JSONStringToList(); } ```
//输出结果:
评价
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术