c# .net 6 中json串的处理

一、Newtonsoft.Json.Linq简介

1、官方文档

官方文档

1、常用对象(个人理解)

常用类 简介
JToken 用于将json字符串转化为便于操作的json对象
JTokenType enum 当前JToken支持的json类型
JProperty 键值对对象,JObject 枚举对象
JArray 相当于json中的数组
JObject 相当于json 中的对象

二、转化json为JToken对象

demo json

[
    {
    "order":"011001063805",
    "config":"XXX",
    "build_event":"MP",
    "linename":"L02",
    "panel":"0X0011_1",
    "unitid":"0X0011_1",
    "createuserid":"AOI",
    "eqpid":"L02OP7501",
    "stepname":"DEMO01",
    "status":"Pass"
    }
]

1、JToken

1.1 转化

JToken jToken = JToken.Parse(result);//将json字符串转换为json对象

1.2 判断JSON 类型

jToken.Type != JTokenType.Array;  // 判断当前JSON对象是否是数组

1.3 获取对象的KEY值

var keyList = jToken[0].Select(x => x.ToObject<JProperty>().Name).ToList(); // 获取json数组第一个对象中的所有key值

1.4 根据key值获取value

var res = from p in jToken
                      select (string)p["order"]; // 返回集合 json数组中所有对象,key为 order 的值集合

2、JTokenType 源码,搭配 jToken.Type 使用

namespace Newtonsoft.Json.Linq
{
    //
    // 摘要:
    //     Specifies the type of token.
    public enum JTokenType
    {
        None,
        Object,
        Array,
        Constructor,
        Property,
        Comment,
        Integer,
        Float,
        String,
        Boolean,
        Null,
        Undefined,
        Date,
        Raw,
        Bytes,
        Guid,
        Uri,
        TimeSpan
    }
}

3 JProperty JArray JObject

JObject rss2 = new JObject(
                    new JProperty("chartProperties",
                        new JObject(
                            new JProperty("rows",
                                new JArray(
                                    from c in rowList
                                    select new JValue(c)
                                    )
                            ),
                            new JProperty("columns",
                                new JArray(
                                    from c in columnList
                                    select new JValue(c)
                                    )
                            )
                        )
                    ),
                    new JProperty("data", rss)
                );
posted @ 2022-05-13 17:10  宵夜没得吃  阅读(2025)  评论(0)    收藏  举报