C# 解析JSON方法

在进行Linq to JSON之前,首先要了解一下用于操作Linq to JSON的类.
类名说明
JObject用于操作JSON对象
JArray用于操作JSON数组
JValue表示数组中的值
JProperty表示对象中的属性,以“key/value”形式
JToken用于存放Linq to JSON查询后的结果
方法一:
object Data = null;
Dictionary<string, object> Dic = new Dictionary<string, object>();
MatchCollection Match = System.Text.RegularExpressions.Regex.Matches(json, @"""(.+?)"": {0,1}(\[[\s\S]+?\]|null|"".+?""|-{0,1}\d*)");//使用正则表达式匹配出JSON数据中的键与值 
foreach (Match item in Match)
{
  try
   {
    if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果数据为null(字符串类型),直接转换成null 
    else Data = item.Groups[2].ToString(); //数据为数字、字符串中的一类,直接写入 
    Dic.Add(item.Groups[1].ToString(), Data);
   }
   catch { }
}
JObject 遍历:
引用命名空间:using Newtonsoft.Json.Linq;
           Dictionary<string, string> dic = new Dictionary<string, string>();
                var p = Newtonsoft.Json.Linq.JObject.Parse(json);
                foreach (Newtonsoft.Json.Linq.JToken child in p.Children())
                {
                    var property1 = child as Newtonsoft.Json.Linq.JProperty;
                    dic.Add(property1.Name.ToString(), property1.Value.ToString());
                }

  上面这种遍历 一般情况下 是用在 不知道属性名称的时候,如果知道属性名称直接用 _jObject["ID"].ToString(),或者_jObject["ID"].Value<string>() 就行了。

Newtonsoft.Json.Linq.JObject _jObject = Newtonsoft.Json.Linq.JObject.Parse("{'Goods':{'GoodsId':'111',GoodsName:'Adidas'},'Mark':'2589'}");
 var _value = _jObject["Goods"]["GoodsId"].ToString();    //取值 结果 : 111  
创建JSON对象:
 Newtonsoft.Json.Linq.JObject staff = new Newtonsoft.Json.Linq.JObject();
 staff.Add(new Newtonsoft.Json.Linq.JProperty("Name", "Jack"));
 staff.Add(new JProperty("Age", 33));
 staff.Add(new JProperty("Department", "Personnel Department"));
 staff.Add(new JProperty("Leader", new JObject(new Newtonsoft.Json.Linq.JProperty("Name", "Tom"), new JProperty("Age", 44), new JProperty("Department", "Personnel Department"))));
创建JSON数组:
Newtonsoft.Json.Linq.JArray arr = new Newtonsoft.Json.Linq.JArray();
arr.Add(new JValue(1));
arr.Add(new JValue(2));
arr.Add(new JValue(3));

json格式:

object jss = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
string js = jss.ToString();


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值