反序列化复杂的JSON对象 [英] Deserializing a complex JSON object

查看:238
本文介绍了反序列化复杂的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 JavaScript.Serializer.Deserializer 反序列化复杂的JSON对象,如下所示:

I use JavaScript.Serializer.Deserializer to deserialize a complex JSON object, as below:

{
    "name": "rule 1",
    "enabled": true,
    "conditions": [{
        "type": "time",
        "time": "17:23:10",
        "days": "125"
    }, {
        "type": "sensor",
        "uid": "10.2.0.1",
        "setpoint1": 12,
        "setpoint2": 18,
        "criterion": 1
    }, {
        "type": "sensor",
        "uid": "10.3.0.1",
        "setpoint1": 12,
        "setpoint2": 18,
        "criterion": 2
    }],
    "actions": {
        "period": 100,
        "single": false,
        "act": [{
            "type": "on",
            "uid": "10.1.0.1"
        }, {
            "type": "sms",
            "message": "Hello World"
        }]
    }
}

我想将其转换为o一些类,如下所示:

And I want to convert it to some classes, like below:

public class Rule
{
    public string name { get; set; }
    public bool enabled { get; set; }
    public List<Condition> conditions { get; set; }
    public List<Action> actions { get; set; }
}

public class Condition
{
    public string type { get; set; }
    public string uid { get; set; }
    public DateTime? time { get; set; }
    public string days { get; set; }
    public double setpoint1 { get; set; }
    public double setpoint2 { get; set; }
    public int criterion { get; set; }
}

public class Action
{
    public int period { get; set; }
    public bool single { get; set; }
    public List<Act> act { get; set; }
}

public class Act
{
    public string type { get; set; }
    public string uid { get; set; }
    public string message { get; set; }
}

反序列化代码段:

json = new JavaScriptSerializer();
Rule rule = (json.Deserialize<Rule>(jsonStr));

如果我简化 Rule 类并声明条件操作作为简单的字符串,可以正常工作。

If I simplify the Rule class and declare conditions and actions as simple strings, it works fine.

但是如果我使用上述类,则会抛出异常:

But if I use the classes like above, it throws an exception:


无法将类型为'System.String'的对象转换为类型为'System.Collections.Generic.List`1 [IoTWebApplication.Condition]'

Cannot convert object of type 'System.String' to type 'System.Collections.Generic.List`1[IoTWebApplication.Condition]'


推荐答案

问题是内部(嵌套的)json被加引号,因此被作为字符串处理。因此,当我删除引号时,它工作正常:

The problem was that the inner (nested) json was quoted and therefore was processed as a string. So when I removed the quotes, it worked fine:

json = new JavaScriptSerializer();
Rule rule = (json.Deserialize<Rule>(jsonStr));

这篇关于反序列化复杂的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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