我正在使用 System.Text.Json。
我有以下型号:
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;
}
我的 Json 是:
{
"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"
}
]
}
]
}
以上内容存储在字符串变量中。
我只是打电话:
var myContacts = JsonSerializer.Deserialize<List<Contacts>>(myJsonString);
我不断收到以下错误:
System.Text.Json.JsonException:'无法转换 JSON 值 到 System.Collections.Generic.List`1[VTMShared.Models.Contacts]。小路: $ |行号: 0 |字节位置内联:1。'
我真的看不出这有什么问题。
您需要反序列化为
Root
并从 Contacts
实例中提取 Root
。
var root = JsonSerializer.Deserialize<Root>(json);
var contacts = root.Contacts;
public class Root
{
[JsonPropertyName("contacts")]
public List<Contact> Contacts { get; set; }
}
public class Contact
{
[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; }
}