【问题标题】:JSON deserialization doesn't want to fit in modelJSON 反序列化不想适应模型
【发布时间】:2019-04-29 19:46:42
【问题描述】:

我正在使用一个返回此 JSON 的服务,当模型中的映射只带我第一个对象但 sms 与其他对象的字段为空时。

这是 JSON:

{
  "cliente": "999999",
  "lote_id": "99999999999999",
  "fecha_recepcion": "2019-04-29 12:31:35",
  "resultado": 0,
  "resultado_t": null,
  "sms_procesados": 2,
  "referecia": "Referencia Prueba",
  "ip": "999.999.99.9",
  "sms": {
    "1": {
      "id": "9999999",
      "numero": "999999999",
      "sms": "tests",
      "fecha_envio": "2019-04-29 12:31:35",
      "ind_area_nom": "cell",
      "precio_sms": "9.00000",
      "resultado_t": "",
      "resultado": "0"
    },
    "2": {
      "id": "8888888",
      "numero": "9999998888",
      "sms": "test",
      "fecha_envio": "2019-04-29 12:31:35",
      "ind_area_nom": "Celular",
      "precio_sms": "9.00000",
      "resultado_t": "",
      "resultado": "0"
    }
  }
}

这是我的模型:

public class ResultadoSms
{
    public string cliente { get; set; }
    public Int64 lote_id { get; set; }
    public string fecha_recepcion { get; set; }
    public Int64 resultado { get; set; }
    public object resultado_t { get; set; }
    public Int64 sms_procesados { get; set; }
    public string referecia { get; set; }
    public string ip { get; set; }
    public Sms sms { get; set; }
}

public class Sms 
{       
    public CuerpoSms CuerpoSms { get; set; }
}

public class CuerpoSms
{
    public string id { get; set; }
    public string numero { get; set; }
    public string sms { get; set; }
    public string fecha_envio { get; set; }
    public string ind_area_nom { get; set; }
    public string precio_sms { get; set; }
    public string resultado_t { get; set; }
    public string resultado { get; set; }
}

我尝试将sms 字段转换为列表,但它仍然是空的。我不明白问题出在哪里,也不明白如何以另一种更简单的方式反序列化对象。

【问题讨论】:

    标签: c# .net json serialization


    【解决方案1】:

    您的模型没有考虑 JSON 中 sms 对象内的 12 等键。您需要使用Dictionary<string, CuerpoSms> 来处理它。

    改变这一行:

    public Sms sms { get; set; }
    

    到这里:

    public Dictionary<string, CuerpoSms> sms { get; set; }
    

    小提琴:https://dotnetfiddle.net/1XiwSF

    【讨论】:

    • 谢谢你的朋友,这是我不明白的,因为在现场有N个对象,无法为每个对象创建一个类,现在它可以工作了!
    • 很高兴我能帮上忙。
    【解决方案2】:

    返回的 JSON 中的sms 是一个具有2 个属性 的对象,它们的结构都与您的CuerpoSms 相同。

    要让它们在您的 C# 代码中自动序列化,您需要:

    public class Sms 
    {       
        [JsonProperty("1")]
        public CuerpoSms CuerpoSms1 { get; set; }
    
        [JsonProperty("2")]
        public CuerpoSms CuerpoSms2 { get; set; }
    }
    

    【讨论】:

    • 谢谢你的回答,我没有指定在sms字段中填充了N个对象并且无法为每个对象创建一个类
    猜你喜欢
    • 2022-01-06
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    • 2020-09-29
    相关资源
    最近更新 更多