I'm having an extremely difficult time parsing multiple arrays out of an array, embedded in several object in JSON.
Basically the json looks like
{
took:8,
success:true,
items:[
keywords:{...},
mainInfo:{
name:'...',
expDate:'...',
targetCities:[...],
targetStates:[...]
},
additionalInfo:{
skills:[],
homeTime:''
}
}
My C# looks like:
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;
}
The error is a Null Reference Exception
, with the info Object reference not set to an instance of an object.
, however it seems that this error jumps around almost unpredictably as I try and change my code to fix the bug.
I am by no means a C# or .NET expert. I had dealt with the language in the past, but I personally do not like it. So forgive me for any stupid error I may have made.
I'm basically stepping through all the items and trying to create a Job
object from each item using the data accordingly.
You forgot to initialize your jobs
field, private List<Job> jobs;
You don't need this private field if you alway generate the jobs list. Use a local variable.
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;
}
I think that you may define allJobs first
List<JObject> allJobs = new List<JObject>();
allJobs=o["items"].Select(t => (JObject)t).ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.