【问题标题】:JsonConvert.DeserializeObject returns null in ActionResult MethodJsonConvert.DeserializeObject 在 ActionResult 方法中返回 null
【发布时间】:2018-04-17 16:46:12
【问题描述】:

我有下一个要反序列化的 Json 文档:

{
  "General": {
    "Items": [
      {
        "fId": "divisionID",
        "frmt": "Text"
      },
      {
        "fId": "wcctOwnerID",
        "frmt": "Text"
      },
      {
        "fId": "qreID",
        "frmt": "Text"
      }
    ]
  }
}

我有这些课程:

public class Item
{        
    [JsonProperty(PropertyName = "fId")]
    public string fId { get; set; }

    [JsonProperty(PropertyName = "frmt")]
    public string frmt { get; set; }
}


public class General
{        
    [JsonProperty(PropertyName = "Items")]
    public List<Item> Items { get; set; }
}

我正在尝试用这一行反序列化:

using (StreamReader r = new StreamReader(HostingEnvironment.ApplicationPhysicalPath + @"\Utils\OptionsByDB.json"))
{
    var json = r.ReadToEnd();
    Utils.General items = JsonConvert.DeserializeObject<Utils.General>(json);                    
}

但它返回 null。我做错了什么?

【问题讨论】:

  • 如果你调试你的代码,json变量有什么值吗?
  • 是的,我的 json 文档中有一个字符串

标签: c# json asp.net-mvc json-deserialization


【解决方案1】:

您的问题是您的 JSON 不是 General 对象。

是一个内部有General对象的对象:

你需要这样的类声明:

public class JsonObject{

     [JsonProperty(PropertyName = "General")]
     public General rootObject {get; set;}
}

然后使用:

var jsonConverted = JsonConvert.DeserializeObject<JsonObject>(json);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 2017-02-23
    相关资源
    最近更新 更多