如何反序列化一个JSON属性,可以使用两个不同的数据类型Json.NET [英] How to deserialize a JSON property that can be two different data types using Json.NET

查看:507
本文介绍了如何反序列化一个JSON属性,可以使用两个不同的数据类型Json.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Json.NET为一个项目,我的工作。
从外部API,我收到的JSON与那些对象的属性,但是当它们是空的'假'被传递。

I'm using Json.NET for a project I'm working on. From an external API, I am receiving JSON with properties that are objects, but when they are empty 'false' is passed.

例如:

data: {
    supplier: {
        id: 15,
        name: 'TheOne'
    }
}

也可以是:

data: {
    supplier: false
}

我应该如何界定供应商属性,以使供应商将反序列化到供应商对象或null。

How should I define the supplier property so that the supplier will be deserialized to a Supplier object or null.

现在我有:

public class Data {
   [JsonProperty("supplier")]
   public SupplierData Supplier { get; set; }
}
public class SupplierData {
    [JsonProperty("id")]
    public int Id { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
}

但现在尝试反序列化时,供应商有假失败的值时。
我希望供应商的属性为null时,JSON值是'假'。

But now when trying to deserialize when supplier has a value of 'false' it fails. I would like the Supplier property to be null when the JSON value is 'false'.

我希望有人知道如何做到这一点。谢谢你。

I hope someone knows how to do this. Thanks.

推荐答案

这可以通过自定义的<一个解决href=\"http://james.newtonking.com/json/help/?topic=html/AllMembers_T_Newtonsoft_Json_JsonConverter.htm\"><$c$c>JsonConverter为你的 SupplierData 类。这里是转换器可能是什么样子:

This can be solved by making a custom JsonConverter for your SupplierData class. Here is what the converter might look like:

class SupplierDataConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(SupplierData));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        if (token.Type == JTokenType.Object)
        {
            return token.ToObject<SupplierData>();
        }
        return null;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, value);
    }
}

要使用它,你需要做的是 [JsonConverter] 属性添加到公司属性在这样的数据类:

To use it, all you would need to do is add a [JsonConverter] attribute to the Supplier property in your Data class like this:

public class Data
{
    [JsonProperty("supplier")]
    [JsonConverter(typeof(SupplierDataConverter))]
    public SupplierData Supplier { get; set; }
}

以下是在动作转换器的一个示范。请注意,演示假设你有某种包含了数据属性的对象,因为JSON在你的问题不能自行站立。我定义了一个名为类 RootObject 为此:

Below is a demonstration of the converter in action. Note that the demo assumes you have some kind of containing object for the data property, since the JSON in your question can't stand on its own. I defined a class called RootObject for this purpose:

public class RootObject
{
    [JsonProperty("data")]
    public Data Data { get; set; }
}

实际演示code如下:

The actual demo code follows:

class Program
{
    static void Main(string[] args)
    {
        string json = @"
        {
            ""data"": 
            {
                ""supplier"": 
                {
                    ""id"": 15,
                    ""name"": ""TheOne""
                }
            }
        }";

        Console.WriteLine("--- first run ---");
        RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
        DumpSupplier(obj.Data.Supplier);

        json = @"
        {
            ""data"": 
            {
                ""supplier"": false
            }
        }";

        Console.WriteLine("--- second run ---");
        obj = JsonConvert.DeserializeObject<RootObject>(json);
        DumpSupplier(obj.Data.Supplier);
    }

    static void DumpSupplier(SupplierData supplier)
    {
        if (supplier != null)
        {
            Console.WriteLine("Id: " + supplier.Id);
            Console.WriteLine("Name: " + supplier.Name);
        }
        else
        {
            Console.WriteLine("(null)");
        }
        Console.WriteLine();
    }
}

这是从上面的输出:

--- first run ---
Id: 15
Name: TheOne

--- second run ---
(null)

这篇关于如何反序列化一个JSON属性,可以使用两个不同的数据类型Json.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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