繁体   English   中英

反序列化复杂的JSON对象

[英]Deserializing a complex JSON object

我使用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]”

您创建的结构不适合您发布的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中获取类

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM