C#自學剛上手,連抄帶研究寫了段JSON資料轉LIST的代碼,但現在有一個疑惑就是,如果我list中的list元素數量是不固定的,要怎么定義?
public struct ToJsonMy
{
public string err_msg { get; set; }
public int ret_code { get; set; }
public List<lasermsg> lasermsgs;
}
public struct lasermsg
{
public List<beamsStruct> beams;
public string device_info;
public struct beamsStruct
{
public int angle { get; set; }
public int dist { get; set; }
public bool is_obstacle { get; set; }
}
}
string json = "[{\"err_msg\":\"error!\",\"ret_code\":\"2\",\"lasermsgs\":[{\"device_info\":\"aaaaaaa!\",\"beams\":[{\"angle\":\"20\",\"dist\":\"5\",\"is_obstacle\":\"false\"}]}]}]";
javascriptserializer js = new javascriptserializer(); //實體化一個能夠序列化資料的類
var list = js.deserialize<list<tojsonmy>>(json); //將json資料轉化為物件型別并賦值給list
int ret_code = list[0].ret_code;
string err_msg = list[0].err_msg;
list<lasermsg.beamsstruct> beamsstructs = list[0].lasermsgs[0].beams;
console.readkey();
就比如說我要轉回list的json資料如下:
{
"stations": [
{
"id": "LM1",
"type": "LocationMark",
"x": 1.23,
"y": 4.56,
"r": 1.57,
"desc": "xxxxx"
},
{
"id": "LM2",
"type": "LocationMark",
"x": -1.23,
"y": 4.56,
"r": 3.14,
"desc": ""
},
{
"id": "CP1",
"type": "ChargePoint",
"x": -1.23,
"y": -4.56,
"r": 0,
"desc": ""
}
],
}
“stations”里的list數量是不固定的,不知道有多少個站點,真心求教!謝謝!
uj5u.com熱心網友回復:
station類的定義呢?你要做的本身就是station物件的List,它的長度也不是固定的,不用啥處理啊。基本資料結構要了解,List是鏈表的實作,是變長的,不是陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/267868.html
標籤:C#
上一篇:關于Picturebox畫圖問題
