【问题标题】:Error deserializing JSON into list of objects将 JSON 反序列化为对象列表时出错
【发布时间】: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。我不太明白。你能澄清那个根对象的样子吗?

标签: c# json


【解决方案1】:

基本上@Jawad 在下面说:

创建名为“CustomerList”的新类并尝试。

public class CustomerList
{
    public List<Customer> Customers { get; set; }
}

private List<Customer> GetCustomersFromFile()
{
  string jsonString = File.ReadAllText(@"database.json", Encoding.UTF8);
  return GetJsonGenericType<List<CustomerList>>(jsonString);
}

private static T GetJsonGenericType<T>(string json)
{
  var generatedType = System.Text.Json.JsonSerializer.Deserialize<T>(json);
   return (T)Convert.ChangeType(generatedType, typeof(T));
}

【讨论】:

  • 这不会编译。
【解决方案2】:

给定的 JSON 描述了一个 对象(以花括号 {...} 开头/结尾)。

有很多 JSON 到 C# 的类生成器,Visual Studio 默认附带这样的工具。

使用https://json2csharp.com/,它将从给定的 JSON 中输出以下行:

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 
    public class Customer
    {
        public int id { get; set; }
        public string name { get; set; }
    }

    public class Root
    {
        public List<Customer> customers { get; set; }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 2012-03-07
    • 2023-03-13
    • 1970-01-01
    • 2013-02-10
    • 2022-01-22
    相关资源
    最近更新 更多