I’m working with an API that returns as JSON response. I’m trying to use System.Text.Json to deserialize the JSON response into a class. I’m receiving a JsonException and could use help understanding what I’m doing wrong.
I call the API and store the JSON response:
var response = await client.PostAsJsonAsync(url, responseValue);
string ApiResponse = await response.Content.ReadAsStringAsync();``
Here’s the output of Console.WriteLine(ApiResponse ):
{"matches":[],"nomatches":[{"Id":"1111111111"},{"Id":"222222222"},{"Id":"33333333333"}],"notfound":[{"Id":"4444444"},{"Id":"5555555555"}]}
I have the following class structure:
public class JsonResp
{
public class Rootobject
{
[JsonPropertyName("matches")]
public Match[] Matches { get; set; }
//public List<Match> Matches { get; set; }
[JsonPropertyName("nomatches")]
//public List<Nomatch> Nomatches { get; set; }
public Nomatch[] Nomatches { get; set; }
[JsonPropertyName("notfound")]
public Notfound[] Notfound { get; set; }
//public List<Notfound> Notfound { get; set; }
[JsonPropertyName("id")]
public object id { get; set; }
}
public class Match
{
public string id { get; set; }
}
public class Nomatch
{
public string id { get; set; }
}
public class Notfound
{
public string id { get; set; }
}
}
I’m trying…
List<Rootobject>? result = JsonSerializer.Deserialize<List<Rootobject>>(ApiResponse);
A JsonException is thrown:
The JSON value could not be converted to System.Collections.Generic.List`1[Test.Models.Response.JsonResp+Rootobject]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
What am I doing wrong?
2
Answers
The JSON shown represents a single object. But you’re trying to deserialize it into a list of objects:
It’s not a list. It’s one object:
you have to fix your API response json string. Instead of " /]" should be "]" for exapmple. You can use string fuctions for this
After this you deserialize json, but use Rootobject instead of collection
and you need to fix these classes too
IMHO if you have only one property id in each class it would be just enough one class instead of several. Also you can remove all JsonPropertyName attributes if add jsonOptions