C#:JSON反序列化时,一个字段可以是不同类型 [英] C#: Deserializing JSON when one field can be different types

查看:360
本文介绍了C#:JSON反序列化时,一个字段可以是不同类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与返回包含非真,假或字符串数​​组的数组JSON的API进行通信。我想反序列化这个JSON和存储布尔值,如果有一个,叫做BOOL数据类型的成功一类的字段,数组,如果有一个,在一个叫做自定义数据类型的结果字段。



什么是最好的去实现这个



一些JSON:

  [
{地位:OK,结果:真正}
{
地位: OK,
结果:
[
{名:李四,UserIdentifier的:ABC,MaxAccounts:2}
]
}
]

我的结果类:

 类结果
{
字符串名称,
串UserIdentifier的,
串MaxAccounts
}

班与API通讯:

 类的API 
{
公共字符串状态{搞定;组; }
公开结果[] {结果得到;组; }
公共BOOL成功{搞定;组; }
}


解决方案

通过JSON.NET你可以写一个自定义的JSON转换器。例如,你可以有以下对象:

 公共类根
{
公共字符串状态{得到;组; }
公开结果结果{搞定;组; }
}

公共类结果
{
公共BOOL?值{搞定;组; }
公共项目[] {项目获取;组; }
}

公共类项目
{
公共字符串名称{;组; }
公共字符串UserIdentifier的{搞定;组; }
公共字符串MaxAccounts {搞定;组; }
}

和您的JSON将反序列化的一个根[]



下面是自定义的JSON转换器可怎么是这样的:

 公共类ResultConverter:JsonConverter 
{
公众覆盖布尔CanConvert(类型的objectType)
{
返回的objectType == typeof运算(结果);
}

公众覆盖对象ReadJson(JsonReader读者,类型的objectType,对象existingValue,JsonSerializer串行)
{
如果(reader.TokenType == JsonToken.Boolean)
{
返回新结果
{
值=(布尔)reader.Value,
};
}

返回新结果
{
项= serializer.Deserialize<项目[]>(阅读器),
};
}

公共覆盖无效WriteJson(JsonWriter作家,对象的值,JsonSerializer串行)
{
//如果你想支持序列化可以实现这个方法以及
抛出新NotImplementedException();
}
}

和则:

 类节目
{
静态无效的主要()
{
变种JSON =
@ [
{
,状态:行,
结果:真
},
{
状态:行,
,结果,:
{
,名:李四,
UserIdentifier的:ABC,,
MaxAccounts:2,
}
]
}
];

VAR设置=新JsonSerializerSettings();
settings.Converters.Add(新ResultConverter());
根[] =根 - JsonConvert.DeserializeObject LT;根[]>(JSON,设置);
//做的结果的东西在这里
}
}


I am communicating with an API that returns JSON containing either true, false or an array of string arrays. I wish to deserialize this JSON and store the boolean value, if there is one, in a class field called Success of data type bool, and the array, if there is one, in a field called Result of a custom data type.

What is the best to go about achieving this?

Some JSON:

[
    {"status":"ok","result":true},
    {
        "status":"ok",
        "result":
        [
            {"name":"John Doe","UserIdentifier":"abc","MaxAccounts":"2"}
        ]
    }
]

My Result class:

class Result
{
    string Name,
    string UserIdentifier,
    string MaxAccounts
}

Class for communicating with the Api:

class Api
{
    public string Status { get; set; }
    public Result[] Result { get; set; }
    public bool Success { get; set; }
}

解决方案

With JSON.NET you could write a custom JSON converter. For example you could have the following objects:

public class Root
{
    public string Status { get; set; }
    public Result Result { get; set; }
}

public class Result
{
    public bool? Value { get; set; }
    public Item[] Items { get; set; }
}

public class Item
{
    public string Name { get; set; }
    public string UserIdentifier { get; set; }
    public string MaxAccounts { get; set; }
}

and your JSON will be deserialized to a Root[].

Here's how the custom JSON converter may look like:

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

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Boolean)
        {
            return new Result
            {
                Value = (bool)reader.Value,
            };
        }

        return new Result
        {
            Items = serializer.Deserialize<Item[]>(reader),
        };
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // If you want to support serializing you could implement this method as well
        throw new NotImplementedException();
    }
}

and then:

class Program
{
    static void Main()
    {
        var json = 
        @"[
            {
                ""status"": ""ok"",
                ""result"": true
            },
            {
                ""status"": ""ok"",
                ""result"": [
                    {
                        ""name"": ""John Doe"",
                        ""UserIdentifier"": ""abc"",
                        ""MaxAccounts"": ""2""
                    }
                ]
            }
        ]";

        var settings = new JsonSerializerSettings();
        settings.Converters.Add(new ResultConverter());
        Root[] root = JsonConvert.DeserializeObject<Root[]>(json, settings);
        // do something with the results here
    }
}

这篇关于C#:JSON反序列化时,一个字段可以是不同类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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