如何反序列化具有不同类型和不同数量元素的JSON数组? [英] How to deserialize a JSON array of elements with different types and varying number of elements?

查看:145
本文介绍了如何反序列化具有不同类型和不同数量元素的JSON数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个JSON数组,其中每个元素具有不同的类型,由type属性指示.可以有多个相同类型的元素,并且元素的数量事先未知.那就是:

I am dealing with a JSON array, where each element is of a different type, indicated by a type attribute. There can be more than one element of the same type, and the number of elements is not known beforehand. That is:

[
  {
    'abc': '0',
    'type': 'a'
  },
  {
    'cde': '10',
    'type: 'b'
  },
  {
    'abc': '20'
    'type': 'a'
  }
]

我需要将这样的数组反序列化为List<A>List<B>.

I need to deserialize such an array into a List<A> and List<B>.

我查看了Json.NET文档,但不确定将什么用于此任务是一个好的策略或功能.任何指针将不胜感激.

I looked into Json.NET documentation but I am not sure what would be a good strategy or feature to use for this task. Any pointers would be appreciated.

推荐答案

假设您的类型都是已知的,则可以将所有元素反序列化为JObject并使用linq将初始数组分成多个列表.

Assuming your types are all known before hand you can deserialize all elements to JObject and use linq to separate the initial array into multiple lists.

您可以声明dbc建议的抽象基本类型,而不是使用List<JObject>,然后实现自定义JsonConverter.

Instead of using List<JObject>, you could declare an abstract base type as dbc suggests then implement a custom JsonConverter.

无论哪种情况,如果您想要每种子类型的单独列表,则需要遍历将初始类型转换为子类型的初始数组.

In either case if you want separate lists of each sub type you will need to iterate over your initial array converting the super type to sub type.

定义您的类型:

class A
{
    public int abc { get; set; }
}

class B
{
    public int cde { get; set; }
}

然后反序列化基本数组,并使用linq拆分为两个单独的列表.

Then deserialize your base array, and use linq to split into two separate lists.

string json = @"[
    {
    'abc': '0',
    'type': 'a'
    },
    {
    'cde': '10',
    'type': 'b'
    },
    {
    'abc': '20',
    'type': 'a'
    }
]";

List<JObject> objs = JsonConvert.DeserializeObject<List<JObject>>(json);

List<A> objectsA = objs.Where(d => d["type"].ToString() == "a").Select(d => d.ToObject<A>()).ToList();
List<B> objectsB = objs.Where(d => d["type"].ToString() == "b").Select(d => d.ToObject<B>()).ToList();

这篇关于如何反序列化具有不同类型和不同数量元素的JSON数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆