JSON不会完全反序列化到C#类

时间:2016-09-27 18:53:43

标签: c# serialization json.net

我试图反序列化一些看起来像这样的JSON:

{
   "Results":{
      "Prediction":{
         "type":"table",
         "value":{
            "ColumnNames":[
               "HT",
               "AT",
               "X",
               "Y",
               "Z"
            ],
            "ColumnTypes":[
               "String",
               "String",
               "Double",
               "Double",
               "Double"
            ],
            "Values":[
               [
                  "Mum",
                  "Dad",
                  "0.172627246490883",
                  "0.171741768332677",
                  "0.65563098517644"
               ],
               [
                  "Father",
                  "Mother",
                  "0.391368227731864",
                  "0.21270005247278",
                  "0.395931719795356"
               ]
            ]
         ]
      }
    }
   }
  }

C#类看起来像这样:

public class RootObject
{
    public Results Results { get; set; }
}

public class Results
{
    public Prediction Prediction { get; set; }
}

public class Prediction
{
    public string type { get; set; }
    public Value value { get; set; }
}

public class Value
{
    string[] ColumnNames { get; set; }
    string[] ColumnTypes { get; set; }
    string[][] Values { get; set; }
}

它反序列化到最终属性"值",这是不匹配的。如果我打开错误处理,看看为什么我收到以下错误:

Additional information: Could not find member 'ColumnNames' on object of type 'Value'. Path 'Results.Prediction.value.ColumnNames', line 1, position 64.

我有一个简单的C#示例,可以重现整个问题:

var derek = @"{""Results"":{""Prediction"":{""type"":""table"",""value"":{""ColumnNames"":[""HT"",""AT"",""X"",""Y"",""Z""],""ColumnTypes"":[""String"",""String"",""Double"",""Double"",""Double""],""Values"":[[""Mum"",""Dad"",""0.172627246490883"",""0.171741768332677"",""0.65563098517644""],[""Father"",""Mother"",""0.391368227731864"",""0.21270005247278"",""0.395931719795356""]]]}}}}";

var returnedObj = JsonConvert.DeserializeObject <RootObject> (derek, settings);

我很确定我的班级与JSON相匹配。为什么它没有反序列化?

1 个答案:

答案 0 :(得分:0)

在C#属性中默认为private,它们需要公开才能被Newtonsoft / Json选中

public class Value
{
    public string[] ColumnNames { get; set; }
    public string[] ColumnTypes { get; set; }
    public string[][] Values { get; set; }
}