I make an API call and deserialize the JSON response. JSON response shown below. I want to take the values from Test1 and add those to a list to then insert into an Excel worksheet.
...
public class Loc
{
public string Area1 { get; set; }
public string Area2 { get; set; }
}
public class Risk
{
public float Test1 { get; set; }
public float Test2 { get; set; }
}
public class Response
{
public Loc loc;
public Risk risk;
}
[
{
"Loc": {
"Area1": "1",
"Area2": "2"
},
"Risk": {
"Test1": 1.14,
"Test2": 1.72
}
},
{
"Loc": {
"Area3": "3",
"Area4": "4"
},
"Risk": {
"Test1": 1.14,
"Test2": 1.71
}
}
]
var records = JsonConvert.DeserializeObject<List<Response>>(apiResult);
When I loop through the deserialized object I can access the values for Test1 and write to the console. But when I loop through and access the same values to add to a list (see below) and loop through that list to see the results I get ConsoleApp.Program+Score
. I'm not sure how to use what I have added to my list - meaning can I access this list to insert data into an Excel worksheet?
foreach (var data in records)
{
Console.WriteLine(data.Risk.Test1);
}
public class Score
{
public float score { get; set; }
}
List<Score> scores = new List<Score>();
foreach (var score in records)
{
scores.Add(new Score
{
score = score.risk.Test1
});
}
foreach (object s in scores)
{
Console.WriteLine(s);
}
Re Jawad's comment thank you. Changed the list I was populating to float and added the Test1 values, instead of what I was doing which was adding the whole object to the list.
Amended:
public class Score
{
public float score { get; set; }
}
List<Score> scores = new List<Score>();
foreach (var score in records)
{
scores.Add(new Score
{
score = score.risk.Test1
});
}
To:
List<float> scores = new List<float>();
foreach (var score in records)
{
scores.Add(score.risk.Test1);
}