【问题标题】:C# Json Deserialize returns nullsC# Json 反序列化返回空值
【发布时间】:2016-12-09 22:00:06
【问题描述】:

所以我有一个 JSON 保存在一个文件中,比如说 test.json。我正在打开文件,以字符串形式读取其中的 JSON,然后尝试将其反序列化为对象。文件打开正确,字符串被读取(但转义出现在字符串中),当我尝试反序列化它时,它为对象的所有字段返回空值,我不明白为什么。

以下是 JSON 在文件中的保存方式:http://pastebin.com/Q6hdiJAD

以下是从文件中读取 JSON 后如何将其保存在我的字符串中:http://pastebin.com/HaB480Ww

这是应该反序列化 JSON 的代码(我从多个文件中获取多个 json 并将它们反序列化并将它们添加到列表中):

List<Root> raw = new List<Root>();    
string[] files = Directory.GetFiles(HostingEnvironment.MapPath("~/Content/Files"));
                foreach (string path in files)
                {
                    using (StreamReader sr = new StreamReader(path))
                    {
                        string json = sr.ReadToEnd();
                        Root root = JsonConvert.DeserializeObject<Root>(json);
                        raw.Add(root);
                    }
                }

这是我的课:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using APIGovApp.Models;

namespace APIGovApp.Classes
{
    public class XmlModel
    {
        public string Staff { get; set; }
        public List<Nomenclator> noms { get; set; }
    }

    public class Root
    {
        public XmlModel nom_localitati { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace APIGovApp.Models
{
    public class Nomenclator
    {
        public int cod_jud { get; set; }
        public int cod { get; set; }
        public int cod_pol { get; set; }
        public string denumire { get; set; }
        public string cod_tpl { get; set; }
        public int cod_postal { get; set; }
        public string cod_sar { get; set; }
        public int cod_loc_jud { get; set; }
        public int loc_cod { get; set; }
        public string are_primarie { get; set; }
        public int cod_fiscal_primarie { get; set; }
        public int cod_politie_tata { get; set; }
        public string sar_cod_mf { get; set; }
        public int cod_siruta { get; set; }
        public int cod_siruta_tata { get; set; }
    }
}

我正在参加一场比赛,我需要尽快完成这项工作。请帮忙。

【问题讨论】:

  • Nomenclator 中的名称与 JSON 不匹配,例如 cod_jud 而不是 JUD_COD。将您的 JSON 上传到 json2csharp.com 以自动生成一组正确的类。

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


【解决方案1】:

在我看来,列表属性的名称不匹配。

在代码中:

public List<Nomenclator> noms { get; set; }

在文件中:

{"NOM_LOCALITATI":{"Staff":null,"rand":

注意 noms 与 rand

将 noms 重命名为 rand 或通过添加以下属性为解析器提供提示:

 [JsonProperty(PropertyName = "rand")]
 public List<Nomenclator> noms { get; set; }

【讨论】:

  • 我是否也应该修改 Nomenclator 类中的字段以匹配每个“rand”中的标签?
  • 我认为 JsonConvert 先尝试区分大小写,然后再尝试不区分大小写,因此它应该可以工作,除非名称不同,在这种情况下您必须对它们执行相同操作。
猜你喜欢
  • 1970-01-01
  • 2022-12-03
  • 2017-07-30
  • 1970-01-01
  • 2020-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多