使用JSON.NET有条件地将JSON字符串或数组属性反序列化为C#对象? [英] Conditionally deserialize JSON string or array property to C# object using JSON.NET?

查看:41
本文介绍了使用JSON.NET有条件地将JSON字符串或数组属性反序列化为C#对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定义的C#对象,该对象基于从第三方API获取的非常复杂的JSON.这是其中的一部分:

I have a defined C# object based off a very complex JSON I'm getting from a third party API. Here's a piece of it:

{"alarmSummary":"NONE"}

C#中的对应属性为:

The corresponding property in C# would be:

public string alarmSummary {get; set;}

然后我将使用典型的JSON.vert从JSON.NET进行转换:

And I would get this converted by using my typical JSONConvert from JSON.NET:

var alarms = JSONConvert.DeserializeObject<MyClass>(jsonString); 

但是,API会以这种格式将警报作为数组放置,如果没有任何字符串,则会将警报放置为"NONE":

However, the API will put alarms in this format, as an array, and "NONE" when there aren't any as a string:

{"alarmSummary" : ["AHHH Something went wrong!!", "I'm on fire!!"]}

在C#中,这意味着必须是:

Which means in C# it would need to be:

public string[] alarmSummary {get; set;}

如果可以的话,我只需要JSONConvert将"NONE"字符串反序列化为只有一个条目的数组.是否可以在此属性上设置条件,还是我必须将整个复杂的JSON字符串进行手工转换?

If I could, I would just have the JSONConvert deserialize the "NONE" string into an array of just one entry. Is there a way to set conditions on this property, or will I have to take the whole complex JSON string and hand convert it?

推荐答案

这应该很简单-您可以将alarmSummary设置为对象,然后具有单独的属性,该属性计算alarmSummary并返回null或数组,具体取决于值.

This one should be easy - you can set your alarmSummary as object and then have separate property that evaluates alarmSummary and returns null or array depending on the value.

    public object alarmSummary { get; set; }

    protected string[] alarmSummaryCasted
    {
        get
        {
            if (alarmSummary is String)
                return null;
            else
                return (string[]) alarmSummary;
        }
    }

这篇关于使用JSON.NET有条件地将JSON字符串或数组属性反序列化为C#对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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