【发布时间】:2014-03-10 00:20:31
【问题描述】:
我很难从一个数组中解析出多个数组,这些数组嵌入在 JSON 中的多个对象中。
基本上json看起来像
{
took:8,
success:true,
items:[
keywords:{...},
mainInfo:{
name:'...',
expDate:'...',
targetCities:[...],
targetStates:[...]
},
additionalInfo:{
skills:[],
homeTime:''
}
}
我的 C# 看起来像:
public class Job{
public string name{get;set;}
public List<string> targetCities{get;set;}
public List<string> targetStates{get;set;}
public List<string> skills{get;set;}
public string homeTime{get;set;}
}
public class Jobs{
private JObject o;
private List<Job> jobs;
public Jobs(string json){
this.o=JObject.Parse(json);
}
public List<Job> toList(){
List<JObject> allJobs=o["items"].Select(t => (JObject)t).ToList();
foreach(JObject i in allJobs){
Job j=new Job();
j.name=(string)i["mainInfo"]["name"];
j.targetCities=i["mainInfo"]["targetCities"].Select(t =>(string)t).ToList();
j.targetStates=i["mainInfo"]["targetStates"].Select(t =>(string)t).ToList();
j.expDate=(string)i["mainInfo"]["expDate"]
j.skills=i["additionalInfo"]["skills"].Select(t =>(string)t).ToList();
j.homeTime=(string)i["additionalInfo"]["homeTime"];
this.jobs.Add(j); //ERROR
}
return this.jobs;
}
错误是Null Reference Exception,信息为Object reference not set to an instance of an object.,但是当我尝试更改代码以修复错误时,似乎此错误几乎不可预测地跳来跳去。
我绝不是 C# 或 .NET 专家。我过去处理过这种语言,但我个人不喜欢它。所以请原谅我可能犯的任何愚蠢的错误。
补充:
我基本上是逐步浏览所有项目并尝试使用相应的数据从每个项目创建一个Job 对象。
【问题讨论】:
-
JObject是如何定义的?
-
这是一个 JSON.net 对象