我正在從文件中讀取Json,當我嘗試使用Newtonsoft Json反序列化它時,它將返回null。我正在構建從http://json2csharp.com/ 的JSON類。我不確定它爲什麼說null是因爲使用StreamReader時引入了\ n,\ r等特殊符號。請幫忙。從文件中讀取json和反序列化總是返回null
的Json
{
"Machine Learning Functions": [{
"Function": "JaccardDistance",
"ArgCount": 2,
"Arg1": "Point1",
"Arg1Type": "Point",
"Arg2": "Point2",
"Arg2Type": "Point",
"Return": "distance",
"ReturnType": "Double"
}],
"Math Functions": [{
"Function": "Cosine",
"ArgCount": 2,
"Arg1": "document1",
"Arg1Type": "String",
"Arg2": "document2",
"Arg2Type": "String",
"Return": "angle",
"ReturnType": "Integer"
}, {
"Function": "SQRT",
"ArgCount": 1,
"Arg1": "SomeNumber",
"Arg1Type": "Integer",
"Return": "Number",
"ReturnType": "Integer"
}]
}
C#代碼(從json2csharp拍攝)
public class MachineLearningFunction
{
public string Function { get; set; }
public int ArgCount { get; set; }
public string Arg1 { get; set; }
public string Arg1Type { get; set; }
public string Arg2 { get; set; }
public string Arg2Type { get; set; }
public string Return { get; set; }
public string ReturnType { get; set; }
}
public class MathFunction
{
public string Function { get; set; }
public int ArgCount { get; set; }
public string Arg1 { get; set; }
public string Arg1Type { get; set; }
public string Arg2 { get; set; }
public string Arg2Type { get; set; }
public string Return { get; set; }
public string ReturnType { get; set; }
}
public class RootObject
{
public List<MachineLearningFunction> MachineLearningFunctions { get; set; }
public List<MathFunction> MathFunctions { get; set; }
}
(我JsonLint及其有效的JSON檢查)這JSON是保存到一個文件中,我讀的時候如下我保留一個斷點,通過引入一些特殊字符如\ n,\ r等來讀取字符串。但是,當我嘗試反序列化斷點時顯示null,並且在遍歷列表時,我得到一個空引用異常。
string json = string.Empty;
using (StreamReader reader = new StreamReader(@"C:\Users\Nikh\OneDrive\Documents\Application/json.txt"))
{
json = reader.ReadToEnd();
}
ParseAndConstructJson(json);
public void ParseAndConstructJson(string json) //Using Newtonsoft json
{
RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
foreach (var item in obj.MachineLearningFunctions)
{
MessageBox.Show(item.Function);
}//DataGrid dg = new DataGrid();
}
感謝它的工作。 – nikhil
@nikhil如果幫助你,你可以標記答案是正確的。 – mybirthname