我正在尝试按如下方式反序列化复杂的JSON对象:
public class StationaryOsbtacle
{
public float latitude { get; set; }
public float longitude { get; set; }
public float cylinder_radius { get; set; }
public float cylinder_height { get; set; }
}
public class MovingObstacle
{
public float latitude { get; set; }
public float longitude { get; set; }
public float altitude_msl { get; set; }
public float sphere_radius { get; set; }
}
public class RootObjectMovingObstacle
{
public List<StationaryOsbtacle> stationary_osbtacles { get; set; }
public List<MovingObstacle> moving_obstacles { get; set; }
}
JSON数据是:
{"stationary_osbtacles": [
{
"latitude": 33.833920,
"longitude": -90.175781,
"cylinder_radius": 20,
"cylinder_height": 200
}
],
"moving_obstacles": [
{
"latitude": 33.833920,
"longitude": -90.175781,
"altitude_msl": 200,
"sphere_radius": 20
}
]}
如何单独反序列化每个属性(纬度,经度等)?
最后我尝试通过标签查看任何变量我正在使用以下代码并获取列表 这段代码在计时器内,我不知道数组的大小是什么
webRequest = (HttpWebRequest)WebRequest.Create("http://" + Ip.ToString() + ":" + Port.ToString() + "....."); // Create a request to get obstacles
webRequest.Method = "GET";
webRequest.KeepAlive = true;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.CookieContainer = cookieJar; //set container for HttpWebRequest
webResponse = (HttpWebResponse)webRequest.GetResponse(); // Get the response.
using (var stream = webResponse.GetResponseStream())
using (var reader = new StreamReader(stream))
{
var outObject = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObjectMovingObstacle>(reader.ReadToEnd());
my_label_latitude.Text = outObject.stationary_osbtacles.......?
}
如何在此处显示标签上的任何实际变量?
答案 0 :(得分:2)
使用Newtonsoft JSON引擎:
var yourClass = Newtonsoft.Json.JsonConvert
.DeserializeObject<RootObjectMovingObstacle>(...);
SO和谷歌上有很多例子。
答案 1 :(得分:-1)
您可以使用Newtonsoft JSON库使用简单的dynamic
对象将任何json字符串解析为对象:
JsonReader jsonReader = new JsonTextReader(new StringReader(strJson)) { DateParseHandling = DateParseHandling.None };
dynamic jsonObj = JObject.Load(jsonReader);