我很难从数组中解析多个数组,嵌入在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
对象。
答案 0 :(得分:4)
您忘记初始化jobs
字段,private List<Job> jobs;
如果您总是生成作业列表,则不需要此私有字段。使用局部变量。
public List<Job> toList()
{
jobs = new List<Job>(); //add this line
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);
}
return this.jobs;
}
答案 1 :(得分:1)
我认为您可以先定义allJobs
List<JObject> allJobs = new List<JObject>();
allJobs=o["items"].Select(t => (JObject)t).ToList();