欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Newtonsoft.Json.Linq 常用方法总结

程序员文章站 2022-04-15 08:15:10
[TOC] 1、Entity to Json 1.1、准备工作 我们以如下的 类举例,其中包含了常用的数据类型: 创建一个 实例: 1.2、Entity to Json 返回不缩进的 Json 字符串 返回: 返回缩进的 Json 字符串 返回: Json 字符串缩进 或者: 其他设置 返回: 1. ......

1、entity to json

1.1、准备工作

我们以如下的 person 类举例,其中包含了常用的数据类型:

public class person
{
    public int id { get; set; }

    public string name { get; set; }

    public datetime birthday { get; set; }

    public bool isvip { get; set; }
    
    public float account { get; set; }

    public string[] favorites { get; set; }
    
    public string remark { get; set; }
}

创建一个 person 实例:

person person = new person
{
    id = 1,
    name = "张三",
    birthday = datetime.parse("2000-01-02"),
    isvip = true,
    account = 12.34f,
    favorites = new string[] { "吃饭", "睡觉" }
};

1.2、entity to json

返回不缩进的 json 字符串

jsonconvert.serializeobject(person)

返回:

{"id":1,"name":"张三","birthday":"2000-01-02t00:00:00","isvip":true,"account":12.34,"favorites":["吃饭","睡觉"],"remark":null}

返回缩进的 json 字符串

jsonconvert.serializeobject(person, formatting.indented);

返回:

{
    "id": 1,
    "name": "张三",
    "birthday": "2000-01-02t00:00:00",
    "isvip": true,
    "account": 12.34,
    "favorites": [
        "吃饭",
        "睡觉"
    ],
    "remark": null
}
json 字符串缩进
private string jsonindentation(string str)
{
    //string str = jsonconvert.serializeobject(entity);
    jsonserializer serializer = new jsonserializer();
    textreader tr = new stringreader(str);
    jsontextreader jtr = new jsontextreader(tr);
    object obj = serializer.deserialize(jtr);
    if (obj != null)
    {
        stringwriter textwriter = new stringwriter();
        jsontextwriter jsonwriter = new jsontextwriter(textwriter)
        {
            formatting = formatting.indented,
            indentation = 4,
            indentchar = ' '
        };
        serializer.serialize(jsonwriter, obj);
        return textwriter.tostring();
    }
    else
    {
        return str;
    }
}

或者:

private string jsonindentation(string json)
{
    jobject obj = jobject.parse(json);
    return obj.tostring();
}

其他设置

jsonserializersettings settings = new jsonserializersettings();
// 设置日期格式
settings.dateformatstring = "yyyy-mm-dd";
// 忽略空值
settings.nullvaluehandling = nullvaluehandling.ignore;
// 缩进
settings.formatting = formatting.indented;

jsonconvert.serializeobject(person, settings);

返回:

{
  "id": 1,
  "name": "张三",
  "birthday": "2000-01-02",
  "isvip": true,
  "account": 12.34,
  "favorites": [
    "吃饭",
    "睡觉"
  ]
}

1.3、json to entity

jsonconvert.deserializeobject<person>(json);

2、linq to json

2.1、创建对象

jobject obj = new jobject();
obj.add("id", 1);
obj.add("name", "张三");
obj.add("birthday", datetime.parse("2000-01-02"));
obj.add("isvip", true);
obj.add("account", 12.34f);
// 创建数组
jarray array = new jarray();
array.add(new jvalue("吃饭"));
array.add(new jvalue("睡觉"));
obj.add("favorites", array);
obj.add("remark", null);

2.2、从 json 字符串创建 jobject

string json = "{\"id\":1,\"name\":\"张三\",\"birthday\":\"2000-01-02t00:00:00\",\"isvip\":true,\"account\":12.34,\"favorites\":[\"吃饭\",\"睡觉\"],\"remark\":null}";

jobject obj = jobject.parse(json);

2.3、从 entity 创建 jobject

jobject obj = jobject.fromobject(person);

用匿名对象创建 jobject

jobject obj = jobject.fromobject(new { name = "jack", age = 18 });

显示:

{
  "name": "jack",
  "age": 18
}

2.2、获取值

int id;
if (obj["id"] != null)
    id = obj["id"].value<int>();

获取数组

newtonsoft.json.linq 不支持直接获取数组,但是可以获取 list,然后再转化为数组。

string[] favorites;
if (obj["favorites"] != null)
    favorites = obj["favorites"].value<list<string>>().toarray();