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