zoukankan      html  css  js  c++  java
  • 【C#】Newtonsoft.Json 中 JArray 添加数组报错:Could not determine JSON object type for type 'xxx'

    有时我们临时需要一个 JSON 字符串,直接拼接肯定不是好方法,但又懒得去定义一个类,这是用 JObject 就会非常的方便。

    但是在 JObject 中添加数组却经常被坑。

    List<string> names = new List<string>
    {
        "Tom",
        "Jerry"
    };
    
    JArray array = new JArray(names);
    
    JObject obj = new JObject()
    {
        { "names", array }
    };
    
    Console.WriteLine(obj);
    

    输出结果:

    {
      "names": [
        "Tom",
        "Jerry"
      ]
    }
    

    非常正确,但如果把 List<string> 换成 List<class> 就不对了。

    public class Person
    {
        public int ID { get; set; }
    
        public string Name { get; set; }
    }
    
    List<Person> persons = new List<Person>
    {
        new Person{ ID = 1, Name = "Tom" },
        new Person{ ID = 2, Name = "Jerry" }
    };
    
    JArray array = new JArray(persons);
    
    JObject obj = new JObject()
    {
        { "names", array }
    };
    
    Console.WriteLine(obj);
    

    这么写会报:Could not determine JSON object type for type 'xxx'

    这是由于自定义类不属于基本类型所致。这是就只能用 JArray.FromObject

    JObject obj = new JObject()
    {
        { "persons", JArray.FromObject(persons) }
    };
    

    序列化结果就正确了。

    {
      "names": [
        {
          "ID": 1,
          "Name": "Tom"
        },
        {
          "ID": 2,
          "Name": "Jerry"
        }
      ]
    }
    
  • 相关阅读:
    java常见异常总结
    敏捷开发的七种主流方法
    转:一位10年Java工作经验的架构师聊Java和工作经验
    Map遍历
    Mybatis中的模糊查询
    Mybatis中动态SQL多条件查询
    J2EE,LAMP和ASP.NET三者比较
    关于加密
    Md5Hash的测试
    CentOS7 修改默认时区为 北京时间
  • 原文地址:https://www.cnblogs.com/gl1573/p/12625839.html
Copyright © 2011-2022 走看看