我正在从一个文件中读取Json,当我尝试使用Newtonsoft Json对其进行反序列化时,它返回null。我正在从http://json2csharp.com/构建JSON类 。我不确定它为什么说null是因为它使用StreamReader时引入的特殊符号如\ n,\ r \ n等。请帮忙。
Json(我查看了JsonLint及其有效的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; }
}
这个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();
}
答案 0 :(得分:3)
您需要在JsonProperty
中使用RootObject
定义属性,以将它们映射到json文件。
public class RootObject
{
[JsonProperty(PropertyName ="Machine Learning Functions")]
public List<MachineLearningFunction> MachineLearningFunctions { get; set; }
[JsonProperty(PropertyName ="Math Functions")]
public List<MathFunction> MathFunctions { get; set; }
}
答案 1 :(得分:0)
从以下位置删除空格: JSON文件中的“机器学习功能”和“数学函数”,它会反复地反序列化您的对象。