阅读 279

【C#】Newtonsoft.Json.Linq 常用方法总结

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();
复制代码
关注下面的标签,发现更多相似文章
评论