(多对象)Json转换成List
写的不好,请大家见谅。
1.Json 格式
{"packages":[{“type”:”aaa”}],"zone_packages":[{"tickettype":[{"ticket_type":"111","ticket_count":"1","trans_num":null,"refund_num":null}],"zone_group":"武汉园博会","ticket_key":"1753626040"}],"order_nbr":"30000000012015090800006524","order_amount":"","order_nbr_original":"150908050106992","order_contacts":"仲秀萍","contacts_tel":"15821311320","order_remark":"","use_date":"20150909","order_status":"8"}
2.定义扩展方法
/// <summary>拆分字符串成为名值字典</summary>
/// <param name="str">要分割字符串的</param>
/// <param name="nameValueSeparator">键值对的分隔符</param>
/// <param name="separators">分割字符</param>
/// <returns>键值对字典</returns>
public static IDictionary<String, String> SplitAsDictionary(this String str, String nameValueSeparator = "=", params String[] separators)
{
var dic = new Dictionary<String, String>();
if (String.IsNullOrWhiteSpace(str)) return dic;
if (String.IsNullOrEmpty(nameValueSeparator)) nameValueSeparator = "=";
if (separators == null || separators.Length < 1) separators = new String[] { ",", ";" };
String[] ss = str.Split(separators, StringSplitOptions.RemoveEmptyEntries);
if (ss == null || ss.Length < 1) return null;
foreach (var item in ss)
{
Int32 p = item.IndexOf(nameValueSeparator);
// 在前后都不行
if (p <= 0 || p >= item.Length - 1) continue;
String key = item.Substring(0, p).Trim();
dic[key] = item.Substring(p + nameValueSeparator.Length).Trim();
}
return dic;
}
3.Json格式解析
public static object ZoneTicket(string json)
{
var doc = json;
//json格式解析
var dicList = doc.Split(new String[] { "\"zone_packages\":[", "\"packages\":[", "\"tickettype\":[", "}]" }, StringSplitOptions.None)
//对每个大类处理,先过滤,再分割为子类
.Select(n => n.Replace("\"", "").Split(new String[] { "},{" }, StringSplitOptions.None)
.Select(k => k.Replace("{", "").Replace("}", "")//对子类过滤
.SplitAsDictionary(":", ","))//提取子类的键值对
.ToArray()).ToList();//列表
return dicList;
}
***************************************