使用json.NET和C#解析JSON数组
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用json.NET和C#解析JSON数组,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2038字,纯文字阅读大概需要3分钟。
内容图文
![使用json.NET和C#解析JSON数组](/upload/InfoBanner/zyjiaocheng/803/13345499e0bd42edbca930ab583cd95f.jpg)
我有一些我需要解析的以下JSON格式的数据:
{
"status":0,
"timestamp":"8:20pm",
"routes":[
{
"directions":[
"E Towne",
"ETP"
],
"routeID":"30"
},
{
"directions":[
"Johnson",
"Observatory"
],
"routeID":"81"
}
]
}
使用json.net,我想得到以下输出:
30 E Towne – ETP
81 Johnson – Observatory
使用下面的代码,我得到以下不正确的输出:
30 E Towne – ETP
81 E Towne – ETP
如何将方向数组项写入相应的routeID项?我的代码:
public class Route
{
public string routeID { get; set; }
public string directions { get; set; }
}
private void routeClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string jsonResults_routes = e.Result;
JObject routeData = JObject.Parse(jsonResults_routes);
JArray routeIdArray = (JArray)routeData["routes"];
JArray routeDirections = (JArray)routeData["routes"][0]["directions"];
List<Route> l = new List<Route>();
for (int i = 0; i < routeIdArray.Count; i++)
{
Route BusRoutes = new Route();
JObject routeIDarrayObject = (JObject)routeIdArray[i];
BusRoutes.routeID = (string)routeIDarrayObject["routeID"];
string sep = " - ";
string bothDirections = String.Join(sep, routeDirections);
List<string> sc = new List<string>();
string[] direction = new string[]{bothDirections};
sc.AddRange(direction);
foreach (string direx in sc)
{
BusRoutes.directions = direx;
}
l.Add(BusRoutes);
}
var newList = l.OrderBy(x => x.routeID).ToList();
lbRoutesData.ItemsSource = newList;
}
解决方法:
@competent_tech在分析中是正确的.如果我可以提出建议,我认为如果你使用实际物体会更自然.例如:
public class RouteInfo
{
public List<string> Directions { get; set; }
public string RouteID { get; set; }
}
public class RouteData
{
public int Status { get; set; }
public string Timestamp { get; set; }
public List<RouteInfo> Routes { get; set; }
}
在你的方法中:
var routeData = JsonConvert.DeserializeObject<RouteData>(e.Result);
return routeData.Routes
.Select(r => new Route
{
routeId = r.RouteID,
directions = String.Join(" - ", r.Directions)
})
.OrderBy(r =-> r.routeId)
.ToList();
或者更自然地以其他方式操纵您的类型对象.
编辑:要获得基于JSON字符串生成类的简单方法,请转到json2csharp.
内容总结
以上是互联网集市为您收集整理的使用json.NET和C#解析JSON数组全部内容,希望文章能够帮你解决使用json.NET和C#解析JSON数组所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。