C# 无法反序列化这个 json

Posted

技术标签:

【中文标题】C# 无法反序列化这个 json【英文标题】:C# Can't get this json deserialized 【发布时间】:2021-09-06 00:37:36 【问题描述】:

我一直在尝试使用 JsonConvert.DeserializeObject() 反序列化 C# 中的对象数组。

我不知道该怎么做。

我尝试使用 List ListFotos = JsonConvert... 我试图修改我的 Fotos 对象,添加一个 List 和一个 List>

请帮帮我。

JSON:


      "error": 
        "id": 0,
        "msg": "OK"
      ,
      "parte": 
        "datos": 
          "id_parte": "",
          "titulo": "",
          "hotel": "",
          "bloque": "",
          "planta": "",
          "habitacion": "",
          "tipo": "",
          "fechacreacion": "",
          "creador": "",
          "departamentocreador": ""
        ,
        "fotos": [
          
            "id_foto": "3574",
            "archivo": "2021060411202834031400.jpg"
          ,
          
            "id_foto": "3575",
            "archivo": "2021060411203492625800.jpg"
          
        ],
        "historico": [
          
            "fechaevento": "",
            "estado": "",
            "observaciones": "",
            "usuarioasignado": "",
            "proveedor": "",
            "tipoterceros": "",
            "fechaaplazado": ""
          ,
          
            "fechaevento": "",
            "estado": "",
            "observaciones": "",
            "usuarioasignado": "",
            "proveedor": "",
            "tipoterceros": "",
            "fechaaplazado": ""
          ,
          
            "fechaevento": "",
            "estado": "",
            "observaciones": "",
            "usuarioasignado": "",
            "proveedor": "",
            "tipoterceros": "",
            "fechaaplazado": ""
          ,
          
            "fechaevento": "",
            "estado": "",
            "observaciones": "",
            "usuarioasignado": "",
            "proveedor": "",
            "tipoterceros": "",
            "fechaaplazado": ""
          ,
          
            "fechaevento": "",
            "estado": "",
            "observaciones": "",
            "usuarioasignado": "",
            "proveedor": "",
            "tipoterceros": "",
            "fechaaplazado": ""
          ,
          
            "fechaevento": "",
            "estado": "",
            "observaciones": "",
            "usuarioasignado": "",
            "proveedor": "",
            "tipoterceros": "",
            "fechaaplazado": ""
          
        ]
      
    

C#:

...
if (item.Key.ToString() == "fotos")

    parte_fotos = item.Value.ToString();
    List<Model.Fotos> fotos = await App.Database.GetFotosAsync();
    Model.Fotos foto = new Model.Fotos();
    foto = JsonConvert.DeserializeObject<Model.Fotos>(parte_fotos);
    foto.ID_Parte = id;

...

我遇到的错误:

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'WorkersApp.Model.Fotos' because the type requires a JSON object (e.g. "name":"value") to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. "name":"value") or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureArrayContract (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract) [0x00058] in <7ca8898b690a4181a32a9cf767cedb1e>:0 
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, System.Object existingValue, System.String id) [0x00012] in <7ca8898b690a4181a32a9cf767cedb1e>:0 
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x0007f] in <7ca8898b690a4181a32a9cf767cedb1e>:0 
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Boolean checkAdditionalContent) [0x000db] in <7ca8898b690a4181a32a9cf767cedb1e>:0 
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader r06-22 12:56:32.085 V/mono-stdout(31636):   at Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00054] in <7ca8898b690a4181a32a9cf767cedb1e>:0 
  at Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0 
  at Newtonsoft.Json.JsonConvert.DeserializeObject (System.String value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) [0x0002d] in <7ca8898b690a4181a32a9cf767cedb1e>:0 
  at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0 
  at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0 
  at 06-22 12:56:32.086 V/mono-stdout(31636):   at WorkersApp.Pageviews.Partes.GetDatosParteFromApi (System.String url, System.String id) [0x0066c] in C:\Users\CGarcia\source\repos\WorkersApp\WorkersApp\WorkersApp\Pageviews\Partes.xaml.cs:155

错误发生在这一行:

foto = JsonConvert.DeserializeObject<Model.Fotos>(parte_fotos);

编辑:

我被要求发帖:

字符串 parte_fotos 包含:

"[\n  \n    \"id_foto\": \"3566\",\n    \"archivo\": \"2021060312461958641800.jpg\"\n  \n]"

Model.Fotos 代码为:

using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
namespace WorkersApp.Model

    public class Fotos
    
        [PrimaryKey]
        public string ID_Foto  get; set; 
        public string ID_Parte  get; set; 
        [NotNull]
        public string Archivo  get; set; 
    

【问题讨论】:

分配给parte_fotos 的实际字符串是什么,以及Model.Fotos 的代码是什么? @LukeStorry 对不起,我忘了补充。我编辑了问题。 【参考方案1】:

这个错误是由于从 JSON 对象到 Fotos 模型的错误转换,为了解决这个问题,首先您必须将 JSON 对象转换为模型,然后从模型中获取 Fotos 列表:

fotos = (JsonConvert.DeserializeObject<Model>(parte_fotos)).parte.fotos;

模型对象如下图:

public class Model

    public Error error  get; set; 
    public Parte parte  get; set; 


public class Error

    public int id  get; set; 
    public string msg  get; set; 


public class Parte

    public Datos datos  get; set; 
    public List<Foto> fotos  get; set; 
    public List<Historico> historico  get; set; 


public class Datos

    public string id_parte  get; set; 
    public string titulo  get; set; 
    public string hotel  get; set; 
    public string bloque  get; set; 
    public string planta  get; set; 
    public string habitacion  get; set; 
    public string tipo  get; set; 
    public string fechacreacion  get; set; 
    public string creador  get; set; 
    public string departamentocreador  get; set; 


public class Foto

    public string id_foto  get; set; 
    public string archivo  get; set; 


public class Historico

    public string fechaevento  get; set; 
    public string estado  get; set; 
    public string observaciones  get; set; 
    public string usuarioasignado  get; set; 
    public string proveedor  get; set; 
    public string tipoterceros  get; set; 
    public string fechaaplazado  get; set; 

【讨论】:

【参考方案2】:

试试

foto = JsonConvert.DeserializeObject<List<Model.Fotos>>(parte_fotos);

【讨论】:

这样做会给我错误:CS0029:无法将 System.Collections.Generics.List 转换为 Model.Fotos。 更改声明变量的方式,您必须将其声明为Model.Fotos foto;,但反序列化现在返回 Model.Fotos 类型的列表 我想我爱你。 XDD 如果可行,欢迎您为答案投票 以防有人在阅读。正如@Massaynus 所说:我改变了我从 Model.Fotos foto 声明“foto”的方式...... TO: List FotoList = new List().【参考方案3】:

你可以试试https://json2csharp.com/ 该站点将 JSON 文档转换为 C# 类...

所以生成的类是:

public class Error

    public int id  get; set; 
    public string msg  get; set; 


public class Datos

    public string id_parte  get; set; 
    public string titulo  get; set; 
    public string hotel  get; set; 
    public string bloque  get; set; 
    public string planta  get; set; 
    public string habitacion  get; set; 
    public string tipo  get; set; 
    public string fechacreacion  get; set; 
    public string creador  get; set; 
    public string departamentocreador  get; set; 


public class Foto

    public string id_foto  get; set; 
    public string archivo  get; set; 


public class Historico

    public string fechaevento  get; set; 
    public string estado  get; set; 
    public string observaciones  get; set; 
    public string usuarioasignado  get; set; 
    public string proveedor  get; set; 
    public string tipoterceros  get; set; 
    public string fechaaplazado  get; set; 


public class Parte

    public Datos datos  get; set; 
    public List<Foto> fotos  get; set; 
    public List<Historico> historico  get; set; 


public class Root

    public Error error  get; set; 
    public Parte parte  get; set; 

您可以通过以下方式访问它:

Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 

【讨论】:

以上是关于C# 无法反序列化这个 json的主要内容,如果未能解决你的问题,请参考以下文章

C# Json反序列化 数据协定类型 无法反序列化 由于未找到必需的数据成员

将 json 反序列化到我的 C# 对象中会出错

无法反序列化json字符串c#

无法在 C# 中反序列化 JSON 结果。输入字符串格式不正确错误

无法将 JSON 字符串反序列化为 C# 对象

无法将 JSON 数组反序列化为 C# 对象 [关闭]