c# json数据解析——将字符串json格式数据转换成对象
网络中数据传输经常是xml或者json,现在做的一个项目之前调其他系统接口都是返回的xml格式,刚刚遇到一个返回json格式数据的接口,通过例子由易到难总结一下处理过程,希望能帮到和我一样开始不会的朋友。
1.json简单对象
json数据:
public struct ToJsonMy
{
public string result { get; set; } //属性的名字,必须与json格式字符串中的"key"值一样。
public string res_info { get; set; }
public string queryorder_info { get; set; } }
转换过程:
public static void JsonMy()
{
string json = Jsonstr("D:\\json\\jsonmy1.txt");//Jsonstr函数读取json数据的文本txt
JavaScriptSerializer js = new JavaScriptSerializer(); //实例化一个能够序列化数据的类
ToJsonMy list = js.Deserialize<ToJsonMy>(json); //将json数据转化为对象类型并赋值给list
string result = list.result;
string res_info = list.res_info;
string queryorder_info = list.res_info;
}
2.json还包含对象
json数据:jsonmy2.txt
public struct ToJsonMy2
{
public string result { get; set; }
public string res_info { get; set; }
public queryorder_info queryorder_info;
}
public struct queryorder_info
{
public string order_num { get; set; }
public string orderdetail { get; set; }
};
转换过程:
public static void JsonMy2()
{
string json = Jsonstr("D:\\json\\jsonmy2.txt");
JavaScriptSerializer js = new JavaScriptSerializer(); //实例化一个能够序列化数据的类
ToJsonMy2 list = js.Deserialize<ToJsonMy2>(json); //将json数据转化为对象类型并赋值给list
string result = list.result;
string res_info = list.res_info;
string order_num = list.queryorder_info.order_num;
string orderdetail = list.queryorder_info.orderdetail;
}
3.json包含对象数组 json数据:jsonmy4.txt
public struct ToJsonMy3
{
public string result { get; set; }
public string res_info { get; set; }
public queryorder_info queryorder_info;
}
public struct queryorder_info
{
public string order_num { get; set; }
public List<orderdetail> orderdetail;//数组处理
};
public struct orderdetail
{
public string CFTUin { get; set; }
public string CancelDeadline { get; set; }
public string CheckInDate { get; set; }
public string CheckOutDate { get; set; }
public string CityID { get; set; }
public string CurrencyCode { get; set; }
public string HotelID { get; set; }
public string HotelName { get; set; }
public string ListID { get; set; }
public string PayAmt { get; set; }
public string PayType { get; set; }
public string RommsCnt { get; set; }
public string SPTransID { get; set; }
public string State { get; set; }
};
转换过程:
public static void JsonMy4()
{
string json = Jsonstr("D:\\json\\jsonmy4.txt");
JavaScriptSerializer js = new JavaScriptSerializer(); //实例化一个能够序列化数据的类
ToJsonMy3 list = js.Deserialize<ToJsonMy3>(json); //将json数据转化为对象类型并赋值给list
string result = list.result;
string res_info = list.res_info;
string order_num = list.queryorder_info.order_num;
List<orderdetail> orderdetail = list.queryorder_info.orderdetail;
string CFTUin = orderdetail[0].CFTUin;
string HotelName = orderdetail[0].HotelName;
string ListID = orderdetail[1].ListID;
string State = orderdetail[2].State;
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。