反序列化复杂的JSON对象
本文关键字:对象 JSON 复杂 反序列化 | 更新日期: 2023-09-27 17:53:58
我使用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
类并将conditions
和actions
声明为简单的strings
,它可以正常工作。
但是如果我像上面那样使用这些类,它会抛出一个异常:
不能转换系统类型的对象。String' to type '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到剪贴板
- 在VS编辑/特殊粘贴/粘贴JSON作为类(上面的代码是由这个创建的)
问题是内部(嵌套)json被引用,因此被作为字符串处理。因此,当我删除引号时,它工作得很好:
json = new JavaScriptSerializer();
Rule rule = (json.Deserialize<Rule>(jsonStr));