我在处理json数据反序列化时,遇到以下格式的json数据:
{
"smtcode": {
"max": "100",
"min": "20",
"uom": "毫米",
"code": "smtcode",
"type": "str",
"label": "SMT领料",
"value": "50",
"comment": "",
"tol_type": "plus",
"dec_count": "2",
"dict_code": "smtcode",
"tolerance": "",
"default_value": ""
},
"smtcode1": {
"max": "100",
"min": "20",
"uom": "毫米",
"code": "smtcode1",
"type": "str",
"label": "SMT领料",
"value": "50",
"comment": "",
"tol_type": "plus",
"dec_count": "2",
"dict_code": "smtcode",
"tolerance": "",
"default_value": ""
}
}
我们可以看到上述json有两个对象,也可能有多个,但他们的内容字段是一致的,只有对象名称不一样,也就是说”smtcode,smtcode1“这部分不一致,实际中也不确定值是什么,这时我们则无法去定义固定的对象是反序列化它。那么我们应该怎么做呢?
1. JsonConvert.DeserializeObject
首先我们只需定义对象中固定那部分字段属性
public class paramConfigs
{
public string label { get; set; }
public string code { get; set; }
public string type { get; set; }
public string tolerance { get; set; }
public string tol_type { get; set; }
public int dec_count { get; set; }
public string uom { get; set; }
public string max { get; set; }
public string min { get; set; }
public string dict_code { get; set; }
public string default_value { get; set; }
public string value { get; set; }
public string comment { get; set; }
}
这时我们则利用Dictionary<string, paramConfigs>可以达到反序列化的目的。
var dict = JsonConvert.DeserializeObject<Dictionary<string, paramConfigs>>(jsonstr);
2.JsonSerializer.Deserialize
使用JsonSerializer.Deserialize的JsonElement类型则不需要定义像上述的paramConfigs子类,只需定义一个JsonElement类型的属性即可,如下
使用时则也非常简单,只需把你的json字符串传入即可
JsonSerializer.Deserialize<JsonElement>(param_configs)