I’m using System.Text.Json.
I have the following models:
public class Contacts
{
[JsonPropertyName("id")]
public long Id { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; } = string.Empty;
[JsonPropertyName("paused")]
public bool Paused { get; set; }
[JsonPropertyName("type")]
public string Type { get; set; } = string.Empty;
[JsonPropertyName("owner")]
public bool Owner { get; set; }
[JsonPropertyName("notification_targets")]
public NotificationTargets? NotificationTargets { get; set; }
[JsonPropertyName("teams")]
public List<Teams>? Teams { get; set; }
}
public class NotificationTargets
{
[JsonPropertyName("email")]
public List<Email>? Email { get; set; }
}
public class Email
{
[JsonPropertyName("severity")]
public string Severity { get; set; } = string.Empty;
[JsonPropertyName("address")]
public string Address { get; set; } = string.Empty;
}
public class Teams
{
[JsonPropertyName("id")]
public long Id { get; set; }
[JsonPropertyName ("name")]
public string Name { get; set; } = string.Empty;
}
My Json is:
{
"contacts": [
{
"id": 14960844,
"name": "firstname test",
"paused": false,
"type": "user",
"owner": true,
"notification_targets": {
"email": [
{
"severity": "HIGH",
"address": "[email protected]"
}
]
},
"teams": [
{
"id": 804736,
"name": "Team 1"
}
]
}
]
}
The above is stored in a string variable.
And I just call:
var myContacts = JsonSerializer.Deserialize<List<Contacts>>(myJsonString);
and I keep receiving the following error:
System.Text.Json.JsonException: ‘The JSON value could not be converted
to System.Collections.Generic.List`1[VTMShared.Models.Contacts]. Path:
$ | LineNumber: 0 | BytePositionInLine: 1.’
I really cannot see what is wrong with this.
2
Answers
You need to deserialize as the
Root
and extract theContacts
from theRoot
instance.Without defining the
Root
class, you can work withJsonDocument
:You can use another
Root
class to deserialize whole JSON, but also you could try doing it without root – then this could be parsed to dictionary with one item: