Error Cannot access child value on Newtonsoft.Json.Linq.JProperty while reading JSON
Solution 1:
try this, it was tested in Visual Studio
var response = client.Execute(request);
var data = JObject.Parse(response.Content)["data"];
List<SearchResults> investigatorList = data.Select(d => new SearchResults {
Name = (string)d["lastName"], Contact = new Contact {Name = (string)d["lastName"]}}).ToList();
result (serialized to json format)
[
{
"Name": "HV",
"Contact": {
"Name": "HV"
}
},
{
"Name": "VF",
"Contact": {
"Name": "VF"
}
}
]
classes
public class Contact
{
public string Name { get; set; }
}
public class SearchResults
{
public string Name { get; set; }
public Contact Contact { get; set; }
}
Solution 2:
Ok im not sure what you doing, cause it's a method im not familiar with. what i do with newtonsoft is i build classes to reflect Json Format. And then deserialize it onto it.
Class:
public class DeserializeJson
{
public DataList ExtractedData;
public DeserializeJson(IRestResponse response)
{
try
{
ExtractedData = JsonConvert.DeserializeObject<DataList>(response.Content);
}
catch(Exception ex)
{
throw new Exception(ex.Message());
}
}
public class DataList
{
public List<Data> Data {get; set;}
public meta meta {get; set;}
public string? links {get;set;}
}
public class Data
{
public int investigatorID {get; set;}
public string firstName {get; set;}
public string middleName {get; set;}
public string lastName {get; set;}
public List<titles> titles {get; set;}
public List<CurrentMembership> {get; set;}
}
public class meta
{
public int totalRecords {get; set;}
public int totalPages {get; set;}
}
public class CurrentMembership
{
public int investigatorCenterMembershipID {get; set;}
public investigatorCenter investigatorCenter {get; set;}
public currentMembershipType currentMembershipType {get; set;}
}
public class titles
{
public int investigatorID {get; set;}
//not sure what additionalDetails could also hold but you have to reflect it
public bool additionalDetails {get; set;}
public DateTime? startDate {get; set;}
public DateTime? endDate {get; set;}
public int displayIndex {get; set;}
public investigatorTitle investigatorTitle{get;set;}
}
public class investigatorTitle
{
public int id {get; set;}
public string name {get; set;}
public bool active {get; set;}
}
public class currentMembershipType
{
public int id {get; set;}
public string name {get; set;}
}
public class investigatorCenter
{
public int id {get; set;}
public string name {get; set;}
public string code {get; set;}
public bool active {get; set;}
}
}
After that i would pass whatever you want as everything there is accessible with linq.
For insance:
Access:
//deserialize
DeserializeJson jsonResponse = new DeserializeJson(response);
//access excample
List<string> InvestigatorList = jsonResponse.ExtractedData.Data.Select(name=>name.lastName).ToList();