【发布时间】:2021-07-22 14:38:52
【问题描述】:
给定以下 json(它是项目根目录中名为 database.json 的文件):
{
"customers": [{
"id": 1,
"name": "Bob"
},
{
"id": 2,
"name": "Mary"
},
{
"id": 3,
"name": "Joe"
}
]
}
还有下面的客户类
public class Customer
{
[JsonProperty("id")]
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonProperty("name")]
[JsonPropertyName("name")]
public string Name { get; set; }
}
反序列化时出错:
private List<Customer> GetCustomersFromFile()
{
string jsonString = File.ReadAllText(@"database.json", Encoding.UTF8);
return GetJsonGenericType<List<Customer>>(jsonString);
}
private static T GetJsonGenericType<T>(string json)
{
var generatedType = System.Text.Json.JsonSerializer.Deserialize<T>(json);
return (T)Convert.ChangeType(generatedType, typeof(T));
}
错误详情:
System.Text.Json.JsonException
HResult=0x80131500
Message=The JSON value could not be converted to System.Collections.Generic.List`1[GroceryStoreAPI.Models.Customer]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
Source=System.Text.Json
StackTrace:
at System.Text.Json.ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType)
at System.Text.Json.JsonSerializer.HandleStartObject(JsonSerializerOptions options, ReadStack& state)
at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
at System.Text.Json.JsonSerializer.ReadCore(Type returnType, JsonSerializerOptions options, Utf8JsonReader& reader)
at System.Text.Json.JsonSerializer.Deserialize(String json, Type returnType, JsonSerializerOptions options)
at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
at GroceryStoreAPI.Data.CustomerRepo.GetJsonGenericType[T](String json) in C:\Users\iamau\source\repos\interview-dotnet3\GroceryStoreAPI\Data\CustomerRepo.cs:line 40
at GroceryStoreAPI.Data.CustomerRepo.GetCustomersFromFile() in C:\Users\iamau\source\repos\interview-dotnet3\GroceryStoreAPI\Data\CustomerRepo.cs:line 33
at GroceryStoreAPI.Data.CustomerRepo..ctor() in C:\Users\iamau\source\repos\interview-dotnet3\GroceryStoreAPI\Data\CustomerRepo.cs:line 18
This exception was originally thrown at this call stack:
[External Code]
GroceryStoreAPI.Data.CustomerRepo.GetJsonGenericType<T>(string) in CustomerRepo.cs
GroceryStoreAPI.Data.CustomerRepo.GetCustomersFromFile() in CustomerRepo.cs
GroceryStoreAPI.Data.CustomerRepo.CustomerRepo() in CustomerRepo.cs
我已经尝试过 Json.Net 并且遇到了类似的错误。
按照here 的建议,我在执行类似操作时也会出错:
string json_object = JsonConvert.DeserializeObject<string>(jsonString);
return JsonConvert.DeserializeObject<List<Customer>>(json_object);
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: {. Path '', line 1, position 1.'
【问题讨论】:
-
您的 json 不是客户列表。它包含一个属性
customers,其中包含一个项目列表。您需要创建一个以客户为属性的 rootObject,类型为客户列表...然后反序列化为该 rootObject。 -
谢谢@Jawad。我不太明白。你能澄清那个根对象的样子吗?