VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • C#教程之c# 解析JSON的几种办法

对比

.NET下几种常见的解析JSON方法
主要类 命名空间 限制 内建LINQ支持
DataContractJsonSerializer System.Runtime.Serialization.Json 通用
JavaScriptSerializer System.Web.Script.Serialization 只能在Web环境使用
JsonArray、JsonObject、JsonValue System.Json 只能在Silverlight中使用
JsonConvert、JArray、JObject、JValue、JProperty Newtonsoft.Json 通用 是(推荐使用)

准备数据

实体类:


    [DataContract]
    public class Person
    {
        [DataMember(Order = 0, IsRequired = true)]
        public string Name { get; set; }

        [DataMember(Order = 1)]
        public int Age { get; set; }

        [DataMember(Order = 2)]
        public bool Alive { get; set; }

        [DataMember(Order = 3)]
        public string[] FavoriteFilms { get; set; }

        [DataMember(Order = 4)]
        public Person Child { get; set; }
    }

定义:


Action<object> log = o => Console.WriteLine(o);
Func<int, int, int> add = (x, y) => x + y;

var p1 = new Person {
    Age = 12,
    Alive = true,
    Name = "lj",
    FavoriteFilms = new[] { "Up", "Avatar" }
};
var p2 = new Person() { Age = 28, Name = "cy", Child = p1 };
            

使用DataContractJsonSerializer

帮助类:


    // using System.Runtime.Serialization.Json;
    
    /// <summary>
    /// 解析JSON,仿Javascript风格
    /// </summary>
    public static class JSON
    {

        public static T parse<T>(string jsonString)
        {
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            {
                return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms);
            }
        }

        public static string stringify(object jsonObject)
        {
            using (var ms = new MemoryStream())
            {
                new DataContractJsonSerializer(jsonObject.GetType()).WriteObject(ms, jsonObject);
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }
    }

用法:


    // 序列化
    var jsonString = JSON.stringify(new[] { p1, p2 });
    log(jsonString == JSON.stringify(new List<Person>() { p1, p2 }));   //true
    log(jsonString);
    // 反序列化,泛型集合
    JSON.parse<List<Person>>(jsonString);
    // 数组转换            
    JSON.parse<Person[]>(jsonString);

输出:


[{"Name":"lj","Age":12,"Alive":true,"FavoriteFilms":["Up","Avatar"],"Child":null
},{"Name":"cy","Age":28,"Alive":false,"FavoriteFilms":null,"Child":{"Name":"lj",
"Age":12,"Alive":true,"FavoriteFilms":["Up","Avatar"],"Child":null}}]

使用JavaScriptSerializer


	// using System.Web.Script.Serialization;
    
    var jser    = new JavaScriptSerializer();
    var json    = jser.Serialize(new List<Person>() { p1, p2 });
    var persons = jser.Deserialize<List<Person>>(json);

使用Silverlight


    // using System.Json
    
    var css = "{ \"#header\" : {background:\"red\"}, layout : [5,4,1],color:\"cyan\" }";
    
    var style = JsonObject.Parse(css) as JsonObject;    
    
    (
    from s in style
    where s.Key == "color"
    select (string)s.Value
    ).First().ToString();	
    // "cyan"
    
    
    // 更多操作
    style["layout"][0] = 22;
    
    var hd = style["#header"];
    style["body>div+p"] = hd;
    style.Remove("#header");
    
    var bd = new JsonObject();
    bd["border"] = "1px solid cyan";
    style["body>div+p"]["#meta"] = bd;
    style.ToString();	
    // {"layout":[22,4,1],"color":"cyan","body>div+p":{"background":"red","#meta":{"border":"1px solid cyan"}}}

使用JSON.NET


    // using Newtonsoft.Json;
    
    var json = JsonConvert.SerializeObject(new[] { p1, p2 });
    var persons = JsonConvert.DeserializeObject<List<Person>>(json);
    var ja = JArray.Parse(jsonString);            
    log(ja);	//注意,格式化过的输出

    1.全局序列化设置
   Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();
   JsonConvert.DefaultSettings = new Func(() =>
   {
     //日期类型默认格式化处理
        setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
             setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";

     //空值处理
            setting.NullValueHandling = NullValueHandling.Ignore;

             //高级用法九中的Bool类型转换 设置
             setting.Converters.Add(new BoolConvert("是,否"));

             return setting;
    });

    2.设置序列化时key为驼峰样式 =CamelCasePropertyNamesContractResolver
    JsonSerializerSettings settings = new JsonSerializerSettings();
    settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    settings.Formatting = Formatting.Indented;

    格式设置  原文:https://blog.csdn.net/u011127019/article/details/72801033


相关教程