【问题标题】:Deserialization from JSON into List of Objects从 JSON 反序列化为对象列表
【发布时间】:2019-04-05 07:21:58
【问题描述】:

我正在尝试将json 文件反序列化为对象列表。 JSON 文件要求我使用UTF8。我正在尝试在下面这样做。

FileStream reader1 = new FileStream(fileName, FileMode.Open, FileAccess.Read);
StreamReader streamReader1 = new StreamReader(reader1, Encoding.UTF8);
string jsonString1 = streamReader1.ReadToEnd();

byte[] byteArray1 = Encoding.UTF8.GetBytes(jsonString1);
MemoryStream stream1 = new MemoryStream(byteArray1);

DataContractJsonSerializer inputSerializer2;
inputSerializer2 = new DataContractJsonSerializer(typeof(List<Country>));
c = (List<Country>)inputSerializer2.ReadObject(stream1);
stream1.Close();

这实际上将文件读入列表,但只保存空值和 0。 它是否正确?从外观上看,所有参考资料都在正确的位置。只是我的课堂上的toString() 搞砸了吗?

谢谢。

编辑: 下面是我试图反序列化的类及其成员变量,以及 JSON 的 sn-p 和我的 toString 覆盖。

[DataContract]
public class Country
{
    #region Member Variables

    private string m_name;
    private string m_capital;
    private string m_region;
    private string m_subRegion;
    private int m_population;
    private List<Currency> m_currency = new List<Currency>();
    private List<Language> m_language = new List<Language>();

//这里是下课

public override string ToString()
    {
        return "The country name is " + Name + "\n" + "The country capital is " + Capital + "\n" + "The country region is " + Region
            + "\n" + "The country sub region is " + SubRegion + "\n" + "The country population is " + Population + "\n"
            + "The country currency is " + Currencies + "\n" + "The country language is " + Languages;
    }

/------------------------------------------ -------------------/

[
{
  "currencies": [
    {
      "code": "AFN",
      "name": "Afghan afghani",
      "symbol": "؋"
    }
  ],
  "languages": [
    {
      "iso639_1": "ps",
      "iso639_2": "pus",
      "name": "Pashto",
      "nativeName": "پښتو"
    },
    {
      "iso639_1": "uz",
      "iso639_2": "uzb",
      "name": "Uzbek",
      "nativeName": "Oʻzbek"
    },
    {
      "iso639_1": "tk",
      "iso639_2": "tuk",
      "name": "Turkmen",
      "nativeName": "Türkmen"
    }
  ],
  "name": "Afghanistan",
  "capital": "Kabul",
  "region": "Asia",
  "subregion": "Southern Asia",
  "population": 27657145
}

]

【问题讨论】:

  • JSON 文件有特殊字符,需要通过 UTF8 读取。
  • 我个人建议使用 Newtonsoft json Nuget 包,因为它使用更广泛,并且使序列化和反序列化更容易newtonsoft.com/json
  • @SomeStudent 我希望我可以,但我的教授希望一切都以这种方式完成。
  • 感谢您的建议。我已经同意您的建议,但仍然收到错误消息。无法从 system.io.streamReader 转换为 system.io.stream。它甚至不让我编译它。
  • @约翰。谢谢你不遗余力地帮助我。我希望我能做同样的事情:(

标签: c# json utf-8 json-deserialization datacontractjsonserializer


【解决方案1】:

所有变量名都需要匹配json,public,并且有getter/setter

    [DataContract]
    public class Country
    {
        [DataMember]  
        public string name { get; set; }
        [DataMember]  
        public string capital { get; set; }
        [DataMember]  
        public string region { get; set; }
        [DataMember]  
        public string subRegion { get; set; }
        [DataMember]  
        public int population { get; set; }
        [DataMember]  
        public Currency[] currencies { get; set; }
        [DataMember]  
        public Language[] languages { get; set; }

        public override string ToString()
        {
            return "The country name is " + name + "\n" + "The country capital is " + capital + "\n" + "The country region is " + region
                   + "\n" + "The country sub region is " + subRegion + "\n" + "The country population is " + population + "\n"
                   + "The country currency is " + currencies + "\n" + "The country language is " + languages;
        }
    }

    [DataContract]  
    public class Currency
    {
        [DataMember]  
        public string code { get; set; }
        [DataMember]  
        public string name { get; set; }
        [DataMember]  
        public string symbol { get; set; }
    }

    [DataContract]
    public class Language
    {
        [DataMember]  
        public string iso639_1 { get; set; }
        [DataMember]  
        public string iso639_2 { get; set; }
        [DataMember]  
        public string name { get; set; }
        [DataMember] 
        public string nativeName { get; set; }
    }

它现在可以工作了,除了ToString(),货币和语言将打印为Currency[]Languages[]。您需要创建另一个函数来打印Currency 成员。

此外,最好将using 用于MemoryStream,以确保自动释放流。

using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString1)))  
{  
    // Deserialization from JSON  
    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(List<Country>));  
    var countries = (List<Country>)deserializer.ReadObject(ms);  
}  

【讨论】:

  • 就是这样!太感谢了。我几乎不好意思打字。
猜你喜欢
  • 2019-11-20
  • 1970-01-01
  • 1970-01-01
  • 2016-05-30
  • 2012-03-07
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多