json串如下:
[{"success":{"axlehead":[{"id":"32","axleName":"A\u578b","trainSerialID_id":"1"},{"id":"33","axleName":"C\u578b","trainSerialID_id":"1"},{"id":"34","axleName":"D\u578b","trainSerialID_id":"1"},{"id":"35","axleName":"E\u578b","trainSerialID_id":"1"},{"id":"36","axleName":"H\u578b","trainSerialID_id":"1"}],"trainserial":[{"id":"1","serialName":"b1"},{"id":"2","serialName":"b2"},{"id":"27","serialName":"CRh390"},{"id":"28","serialName":"CRh390"},{"id":"29","serialName":"CRh390"}]}}]格式化的样式为:
json串中包含一个标识符 success,以及几个 list数据。
以下为处理的关键代码:
//以下代码中 , axlehead 及 trainserial 均为实体类 private void getJsonData(string jsonStr) { List<Dictionary<string, Dictionary<string, List<object>>>> deserialResult = (List<Dictionary<string, Dictionary<string, List<object>>>>)JsonConvert.DeserializeObject<List<Dictionary<string, Dictionary<string, List<object>>>>>(jsonStr); if (deserialResult[0].Keys.First().Equals("success")) { Dictionary<string, List<object>> dict_val = deserialResult[0]["success"]; List<axlehead> listAxlehead = getListByClassType<axlehead>(dict_val["axlehead"]); List<trainserial> listTrainseriale = getListByClassType<trainserial>(dict_val["trainserial"]); } } private List<T> getListByClassType<T>(List<object> sourceList) { List<T> listReturn = new List<T>(); foreach (object obj in sourceList) { T tmp = JsonConvert.DeserializeObject<T>(obj.ToString()); listReturn.Add(tmp); } return listReturn; }
使用泛型封装的一种写法:
private void getJsonData(string jsonStr) { List<Dictionary<string, Dictionary<string, List<object>>>> deserialResult = (List<Dictionary<string, Dictionary<string, List<object>>>>)JsonConvert.DeserializeObject<List<Dictionary<string, Dictionary<string, List<object>>>>>(jsonStr); if (deserialResult[0].Keys.First().Equals("success")) { Dictionary<string, List<object>> dict_val = deserialResult[0]["success"]; List<axlehead> listAxlehead = new List<axlehead>(); List<trainserial> listTrainseriale = new List<trainserial>(); getManyListByJson<axlehead, trainserial>(dict_val, "axlehead", out listAxlehead, "trainserial", out listTrainseriale); } } private void getManyListByJson<T1, T2>(Dictionary<string, List<object>> dict_DataSource, string tableName1, out List<T1> list1, string tableName2, out List<T2> list2) { list1 = getListByClassType<T1>(dict_DataSource[tableName1]); list2 = getListByClassType<T2>(dict_DataSource[tableName2]); } private List<T> getListByClassType<T>(List<object> sourceList) { List<T> listReturn = new List<T>(); foreach (object obj in sourceList) { T tmp = JsonConvert.DeserializeObject<T>(obj.ToString()); listReturn.Add(tmp); } return listReturn; }