I want to deserialize the JSON response from the web service call in the C# Console application.JSON looks like
{
"il_response": {
"custom_forms": [
{
"id": 84,
"name": "Request",
"note": "Notes",
"fields": [
{
"label": "Prj",
"value": [
"ABC",
"DEF"
],
"name": "Projects"
},
{
"label": "Submit Date",
"value": "October 16, 2017 ",
"name": "Submit Date"
},
{
"label": "Name",
"value": "Dhana",
"name": "Name"
}
]
}
],
"il_metadata": {}
}
}
I have all the POCO in the seperate class file called iDTO.cs
public class iResponse
{
public iResponse(){ }
public List<iDTO> data { get; set; }
}
public class iDTO
{
public iDTO() { }
}
public class Field
{
public string label { get; set; }
public object value { get; set; }
public string name { get; set; }
}
public class C_Form
{
public int id { get; set; }
public string name { get; set; }
public string note { get; set; }
public List<Field> fields { get; set; }
}
public class IlMetadata
{
}
public class IlResponse
{
public List<C_Form> c_forms { get; set; }
public IlMetadata il_metadata { get; set; }
}
public class RootObject
{
public IlResponse il_response { get; set; }
}
Below is my code where I am calling the service
public class APICall
{
string BaseUR = ConfigurationManager.AppSettings["BaseURL"];
string accessToken = ConfigurationManager.AppSettings["AccessToken"];
public async Task<IHttpActionResult> Get()
{
using (var client = new HttpClient())
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
Uri uri = new Uri(BaseURL);
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
var response = await client.GetAsync(uri);
var datafile = await response.Content.ReadAsStringAsync();
var returnDataObj = JsonConvert.DeserializeObject<iLabDTO.RootObject>(datafile);
}
}
}
Here I am not sure how to get each name and value property from the field in the JSON. I see that we can use the for each with the fields but not surehow to get both the value and name
This worked using your json, after amending the problem mentioned by Luke. However I'm using iDTO.RootObject
whereas your api says iLabDTO.RootObject
.
string datafile = File.ReadAllText(@"json.txt");
var returnDataObj = JsonConvert.DeserializeObject<iDTO.RootObject>(datafile);
foreach (var form in returnDataObj.il_response.c_forms)
{
Console.WriteLine(form.id);
Console.WriteLine(form.name);
Console.WriteLine(form.note);
foreach(var field in form.fields)
{
Console.WriteLine(field.name);
Console.WriteLine(field.label);
Console.WriteLine(field.value);
}
}