【发布时间】: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