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?**
CodePudding user response:
The JSON shown represents a single object. But you're trying to deserialize it into a list of objects:
List<Rootobject>? result= JsonSerializer.Deserialize<List<Rootobject>>(ApiResponse);
It's not a list. It's one object:
Rootobject? result= JsonSerializer.Deserialize<Rootobject>(ApiResponse);
CodePudding user response:
you have to fix your API response json string. Instead of " /]" should be "]" for exapmple. You can use string fuctions for this
ApiResponse = ApiResponse.Replace("\\]","]").Replace("\\[","[");
After this you deserialize json, but use Rootobject instead of collection
Rootobject? result = System.Text.Json. JsonSerializer.Deserialize<Rootobject?>(ApiResponse );
and you need to fix these classes too
public class Match
{
[JsonPropertyName("Id")]
public string id { get; set; }
}
public class Nomatch
{
[JsonPropertyName("Id")]
public string id { get; set; }
}
public class Notfound
{
[JsonPropertyName("Id")]
public string id { get; set; }
}
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
var jsonOptions = new System.Text.Json.JsonSerializerOptions
{ PropertyNameCaseInsensitive = true };
Rootobject? result= System.Text.Json.
JsonSerializer.Deserialize<Rootobject?>(ApiResponse,jsonOptions );