【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"
    }
  ]
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在递归的数组移除特定条件的属性,你可以使用递归函数来遍历`JObject`和`JArray`对象,并根据条件移除属性。以下是一个示例代码: ```csharp using Newtonsoft.Json.Linq; public static void RemoveProperties(JToken token, string propertyName) { if (token.Type == JTokenType.Object) { // 遍历对象属性 foreach (var child in token.Children<JProperty>().ToList()) { if (child.Name == propertyName) { // 移除满足条件的属性 child.Remove(); } else { // 递归处理子属性 RemoveProperties(child.Value, propertyName); } } } else if (token.Type == JTokenType.Array) { // 遍历数组元素 foreach (var child in token.Children().ToList()) { // 递归处理数组元素 RemoveProperties(child, propertyName); } } } // 示例用法 string json = @" { 'name': 'John', 'age': 30, 'children': [ { 'name': 'Alice', 'age': 5, 'children': [ { 'name': 'Bob', 'age': 10 } ] }, { 'name': 'Emma', 'age': 8 } ] }"; JObject obj = JObject.Parse(json); // 移除所有属性名为 "age" 的属性 RemoveProperties(obj, "age"); // 输出结果 Console.WriteLine(obj.ToString()); ``` 在上面的示例,我们定义了一个递归函数`RemoveProperties`,该函数用于遍历`JObject`和`JArray`对象,根据条件移除属性。然后,我们使用这个函数移除了所有属性名为 "age" 的属性。最后,我们将修改后的`JObject`对象输出到控制台。 输出结果将不包含任何名为 "age" 的属性: ``` { "name": "John", "children": [ { "name": "Alice", "children": [ { "name": "Bob" } ] }, { "name": "Emma" } ] } ``` 希望这能满足你的需求!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值