just started to playing with C#, and I want to populate field from json (want to show each event)
Here is my json information which I am using:
[
{
"event": {
"date": "December 2, 2022, 20:00 pm",
"id": "12345",
"day": "December 2",
"hour": "20:00 pm",
"year": "2022",
"event": "wedding",
},
"test": [
{
"test1": {
"avg": 100,
"max": 160
},
"test2": {
"avg": 130,
"max": 150
},
"test3": {
"avg": 180,
"max": 200
}
}
]
},
{
"event": {
"date": "December 3, 2022, 20:00 pm",
"id": "34567",
"day": "December 3",
"hour": "20:00 pm",
"year": "2022",
"event": "birthday",
},
"test": [
{
"test1": {
"avg": 200,
"max": 250
},
"test2": {
"avg": 50,
"max": 60
},
"test3": {
"avg": 70,
"max": 80
}
}
]
}
]
Lets say I want to show test for each events in Console, I created a code like:
public class Test
{
public double avg { get; set; }
public double max { get; set; }
}
public class Test2
{
public double avg { get; set; }
public double max { get; set; }
}
public class Test3
{
public double avg { get; set; }
public double max { get; set; }
}
public class Test
{
public Test1 test1 { get; set; }
public Test2 test2 { get; set; }
public Test3 test3 { get; set; }
}
public class Root
{
public Event event { get; set; }
public List<Test> tests { get; set; }
}
private static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
string link = "myurl";
WebRequest request = WebRequest.Create(link);
request.ContentType= "application/json";
var Token = "mytoken";
request.Headers.Add("Authorization", "Bearer " Token);
WebResponse response = request.GetResponse();
using (Stream datastream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(datastream);
string responsefromserver = reader.ReadToEnd();
Root root = JsonConvert.DeserializeObject<Root>(responsefromserver);
//here I want to show test for each event
}
Console.ReadKey();
}
}
So, how can I show event in Console? I got error when run the code: Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Program Root' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
If you could give me some hints it would be great
CodePudding user response:
There appears to be a mismatch between your JSON and your object structure. The root of your JSON is not an object with an event
property. It is an array of objects, each of which has an event
property.
Update your Root
class to correct the property:
public class Root
{
public Event event { get; set; }
}
And update your deserialization to match the array in the JSON data:
Root root = JsonConvert.DeserializeObject<List<Root>>(responsefromserver);
Then you can loop over your objects and output whatever data you like:
foreach (var obj in root)
{
Console.WriteLine($"Event: {obj.event.event}");
}