json解析
2016-12-07 11:39
344 查看
我自己用到的一个json解析方法
因为json的格式比较古怪,网上很多方法解析不出来,不过解析原理是相同的,只是类的格式不一样而已。
下面是需要解析的json字符串,我把它的格式变换了一下:
需要生成的类
解析方法
因为json的格式比较古怪,网上很多方法解析不出来,不过解析原理是相同的,只是类的格式不一样而已。
下面是需要解析的json字符串,我把它的格式变换了一下:
"{ \"title\": \"newFlow_1\", \"nodes\": { \"demo_node_1\": { \"name\": \"开始\", \"left\": 282, \"top\": 85, \"type\": \"start\", \"width\": 100, \"height\": 24, \"alt\": true }, \"demo_node_2\": { \"name\": \"结束\", \"left\": 281, \"top\": 176, \"type\": \"end\", \"width\": 100, \"height\": 24, \"alt\": true } }, \"lines\": { \"demo_line_3\": { \"type\": \"sl\", \"from\": \"demo_node_1\", \"to\": \"demo_node_2\", \"name\": \"\", \"alt\": true } }, \"areas\": { }, \"initNum\": 4 }"
需要生成的类
public class Info { public string title; public Dictionary<string, Nodes> nodes; public Dictionary<string, Lines> lines; public object areas; public int initNum; } public class Nodes { public string name; public string left; public string top; public string type; public string width; public string height; public string alt; public string role; public string bumen; public string tasktype; public string Approvaltype; } public class Lines { public string type; public string name; public string from; public string to; public string alt; }
解析方法
// infolist为需要解析的字符串 JavaScriptSerializer js = new JavaScriptSerializer(); Info info = js.Deserialize<Info>(infolist); foreach (KeyValuePair<string, Nodes> dict in info.nodes) { Nodes nodes = dict.Value; T_NODESINFO dto = new T_NODESINFO(); dto.CODE = dict.Key; dto.LEFT = nodes.left; dto.TOP = nodes.top; dto.TYPE = nodes.type; dto.NAME = nodes.name; dto.FLOWID = flowid; dto.APPROVALTYPE = nodes.Approvaltype; dto.ROLE = nodes.role; dto.TASKTYPE = nodes.tasktype; dto.BUMENID = nodes.bumen; BLLFactory<T_NODESINFO>.GetBaseService.EntityAdd(dto); } //获取所有线的集合 foreach (KeyValuePair<string, Lines> dict in info.lines) { Lines lines = dict.Value; T_LINEINFO dto = new T_LINEINFO(); dto.CODE = dict.Key; dto.FROM = lines.from; dto.TO = lines.to; dto.FLOWID = flowid; BLLFactory<T_LINEINFO>.GetBaseService.EntityAdd(dto); }