我有一些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–天文台
使用下面的代码,我得到了以下错误的输出:
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在is分析中是正确的。如果我可以求婚,我想如果你用实际的物体工作,会感觉更自然。例如:
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。
这是因为routeDirections特别要求数组中的第一个元素:
JArray routeDirections = (JArray)routeData["routes"][0]["directions"];
您需要在循环中移动此逻辑,并使用当前的循环索引器:
for (int i = 0; i < routeIdArray.Count; i++)
{
Route BusRoutes = new Route();
JObject routeIDarrayObject = (JObject)routeIdArray[i];
BusRoutes.routeID = (string)routeIDarrayObject["routeID"];
JArray routeDirections = routeIDarrayObject["directions"];