Json.NET:单个属性的不同JSON模式 [英] Json.NET: Different JSON schemas for a single property

查看:61
本文介绍了Json.NET:单个属性的不同JSON模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个第三方API,该API对其返回的JSON对象进行快速和松散的播放.在C#中,我试图设置Json.NET来将这些JSON对象反序列化为类,但是遇到了麻烦:有时,根据上下文,同一属性名称将用于几种不同的模式.

I'm working with a third-party API that plays fast and loose with its returned JSON objects. In C#, I'm trying to set up Json.NET to deserialize these JSON objects to classes, but I've run into a hitch: sometimes the same property name will be used with several different schemas, depending on context.

这是JSON数据结构的示例:

Here's an example of the JSON data structure:

{
    "examples": [{
            "data": "String data",
            "type": "foo"
        }, {
            "data": {
                "name": "Complex data",
                "19": {
                    "owner": "Paarthurnax"
                }
            },
            "type": "complex"
        }, {
            "data": {
                "name": "Differently complex data",
                "21": {
                    "owner": "Winking Skeever"
                }
            },
            "type": "complex"
        }
    ]
}

在发现这种不一致之前,我用此类表示了第一个示例:

Before discovering this inconsistency, I represented the first example with this class:

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

    [JsonProperty("type"]
    public string DataType {get; set;}
}

# In the main method
Example deserializedObject = JsonConvert.DeserializeObject<Example>(stringData);

现在,这种方法存在两个问题:

Now, there are two problems with this approach:

  1. 数据"键具有两种不同的属性类型.有时是字符串,有时是对象.我可以为内部对象创建一个自定义类,但随后Json.NET会抱怨字符串版本.
  2. 当数据"是一个对象时,其属性名称不一致-请注意,第二个数据条目具有称为19的属性,而第三个数据条目具有称为21的属性.这些对象的结构相同,但是由于它们的键名相同是不同的,我不能直接将它们映射到类.

第一个问题是更紧迫的问题.

The first issue is the more pressing one.

我知道我可以使用 JsonExtensionData 解决问题如有必要,但我不确定这是否是最好的方法,并且它在我的应用程序中没有提供任何编译时安全性.

I know that I could solve the issue using JsonExtensionData if necessary, but I'm not sure if this is the best way, and it doesn't provide any compile-time safety in my application.

将JSON反序列化为C#类的最佳方式是什么?

What is the best way for me to deserialize this JSON into a C# class?

推荐答案

您可以使用

You can use a JsonConverter. Here's a fully functioning example:

public class Example
{
    public string StringData { get; set; }

    public ComplexData ComplexData { get; set; }

    public string Type { get; set; }
}

public class ComplexData
{
    public string Name { get; set; }

    [JsonProperty("19")]
    public Foo Nineteen { get; set; }

    [JsonProperty("21")]
    public Foo TwentyOne { get; set; }
}

public class Foo
{
    public string Owner { get; set; }
}

public class FlexibleJsonConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var examples = new List<Example>();
        var obj = JObject.Load(reader);
        foreach (var exampleJson in obj["examples"])
        {
            var example = new Example { Type = (string)exampleJson["type"] };
            if (example.Type == "complex")
            {
                example.ComplexData = exampleJson["data"].ToObject<ComplexData>();
            }
            else
            {
                example.StringData = (string)exampleJson["data"];
            }

            examples.Add(example);
        }

        return examples.ToArray();
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsAssignableFrom(typeof(Example[]));
    }
}

private static void Main()
{
    var json = @"{
                    ""examples"": [{
                            ""data"": ""String data"",
                            ""type"": ""foo""
                        }, {
                            ""data"": {
                                ""name"": ""Complex data"",
                                ""19"": {
                                    ""owner"": ""Paarthurnax""
                                }
                            },
                            ""type"": ""complex""
                        }, {
                            ""data"": {
                                ""name"": ""Differently complex data"",
                                ""21"": {
                                    ""owner"": ""Winking Skeever""
                                }
                            },
                            ""type"": ""complex""
                        }
                    ]
                }";

    var examples = JsonConvert.DeserializeObject<IEnumerable<Example>>(json, new FlexibleJsonConverter());

    foreach (var example in examples)
    {
        Console.WriteLine($"{example.Type}: {example.StringData ?? example.ComplexData.Nineteen?.Owner ?? example.ComplexData.TwentyOne.Owner}");
    }

    Console.ReadKey();
}

这篇关于Json.NET:单个属性的不同JSON模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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