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

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

问题描述

我正在将 Json.NET 用于我正在处理的项目.我从外部 API 接收带有对象属性的 JSON,但是当它们为空时,会传递false".

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
}

我应该如何定义供应商属性,以便将供应商反序列化为供应商对象或为空.

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; }
}

但是现在当供应商的值为false"时尝试反序列化它失败了.当 JSON 值为false"时,我希望供应商属性为 null.

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.

推荐答案

这可以通过自定义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] 属性添加到 Data 类中的 Supplier 属性,例如这个:

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; }
}

下面是转换器的运行演示.请注意,该演示假定您有某种包含 data 属性的对象,因为您问题中的 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; }
}

实际演示代码如下:

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.NET 反序列化可以是两种不同数据类型的 JSON 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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