c# 解析JSON的几种办法
2021-06-15 04:04
标签:data remove 使用 select 反序列化 fun jar 准备 对比 实体类: 定义: 帮助类: 用法: 输出: 输出: c# 解析JSON的几种办法 标签:data remove 使用 select 反序列化 fun jar 准备 对比 原文地址:https://www.cnblogs.com/chxl800/p/10387220.html对比
主要类
命名空间
限制
内建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
使用DataContractJsonSerializer
// using System.Runtime.Serialization.Json;
///
// 序列化
var jsonString = JSON.stringify(new[] { p1, p2 });
log(jsonString == JSON.stringify(new List
>(jsonString);
// 数组转换
JSON.parse
[{"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
>(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
>(json);
var ja = JArray.Parse(jsonString);
log(ja); //注意,格式化过的输出
[
{
"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
}
}
]