反序列化复杂的JSON对象

时间:2016-07-02 14:15:39

标签: c# json deserialization

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

{
    "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"
        }]
    }
}

我想将它转换为某些类,如下所示:

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类并将conditionsactions声明为简单strings,那么它可以正常工作。

但是如果我使用上面的类,它会引发异常:

  

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

2 个答案:

答案 0 :(得分:1)

您创建的结构不适合您发布的JSON。

应该看起来像

public class Rule
{
    public string name { get; set; }
    public bool enabled { get; set; }
    public Condition[ ] conditions { get; set; }
    public Actions actions { get; set; }
}

public class Actions
{
    public int period { get; set; }
    public bool single { get; set; }
    public Act[ ] act { get; set; }
}

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

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

在大多数情况下,VS很容易将类直接从JSON中取出

答案 1 :(得分:0)

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

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