如何使用Newtonsoft反序列化可以是数组或字典的对象? [英] How to deserialize object that can be an array or a dictionary with Newtonsoft?

查看:203
本文介绍了如何使用Newtonsoft反序列化可以是数组或字典的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个API,该API返回需要反序列化的json对象.我的问题是这些对象的成员之一有时是一个空数组("[]"),有时是一个字典("{" 1:{...}," 2:{...}}" ).我想将其反序列化为数组或字典,因为我不关心ID,所以我只想要所有对象的列表.这是我反序列化对象的方式:

I am using an API that returns a json object that I need to deserialize. My problem is that one of the members of those object is sometimes an empty array ("[]") and sometimes a dictionary ("{"1":{...}, "2":{...}}"). I want to deserialize it into either an array or a dictionary, since I don't car about the IDs, I just want a list of all the objects. Here is how I deserialize the object:

var response = JsonConvert.DeserializeObject<Response>(json);

这是Response类的定义:

And here is the definition of the Response class:

public class Response
{
    [JsonProperty(PropertyName = "variations")]
    public Dictionary<int, Variation> Variations { get; set; }
}

当Response在变体字段中包含字典时,它会很好地工作,但是在包含空数组时,它会失败.我从Newtonsoft得到一个错误,说不能将数组反序列化为字典.如果将Variations属性定义为数组,则它适用于空数组,但是当它是字典时会失败.我该怎么做才能正确地反序列化两个可能的值,或者忽略空数组,并且当它是数组而不是失败时将Variations设置为null.

It works well when the Response contains a dictionary in it's variations field, but it fails when it contains an empty array. I'm getting an error from Newtonsoft saying that an array cannot be deserialized into a dictionary. If I define the Variations property as an array, it works for empty arrays, but it fails when it is a dictionary. What could I do to either deserialize correctly both possible values, or to ignore empty arrays and set Variations to null when it's an array instead of failing.

谢谢.

推荐答案

这是我使用的解决方案:

Here is the solution I used :

    public Dictionary<int, Variation> Variations
    {
        get
        {
            var json = this.VariationsJson.ToString();
            if (json.RemoveWhiteSpace() == EmptyJsonArray)
            {
                return new Dictionary<int, Variation>();
            }
            else
            {
                return JsonConvert.DeserializeObject<Dictionary<int, Variation>>(json);
            }
        }
    }

    [JsonProperty(PropertyName = "variations")]
    public object VariationsJson { get; set; }

基本上,变体首先在基本对象中反序列化.当我想读取值时,我检查对象是否为空数组,如果是,则返回空字典.如果该对象是好的字典,则将其反序列化并返回.

Basically, the variations are first deserialized in a basic object. When I want to read the value, I check if the object is an empty array, and if so I return an empty dictionary. If the object is a good dictionary, I deserialize it and return it.

这篇关于如何使用Newtonsoft反序列化可以是数组或字典的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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