2016-12-06 46 views
2

我正在從文件中讀取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(); 
} 

回答

3

你需要與你的JsonPropertyRootObject屬性來定義將它們映射到JSON文件。 在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; } 
} 
+0

感謝它的工作。 – nikhil

+0

@nikhil如果幫助你,你可以標記答案是正確的。 – mybirthname

0

從刪除空格。