在C#中反序列化JSON数据

时间:2014-12-07 12:37:58

标签: c# json json.net

我是处理JSON数据的新手,我正在尝试从AWS网站反序列化定价数据。我已经构建了我的类(我做了一个Paste Special>粘贴JSON数据作为类)但是当我尝试反序列化时,它会在Config类中出现。我相信我要么需要创建一个字典或做一个List,但我不确定如何正确嵌套。我尝试过不同的东西,但似乎没什么用。指出我正确的方向让我能够理解它是非常感激的。

    public class Rootobject
    {
        public float vers { get; set; }
        public Config config { get; set; }
    }

    public class Config
    {
        public string rate { get; set; }
        public string valueColumns { get; set; }
        public string currencies { get; set; }
        public Region regions { get; set; }
    }

    public class Region
    {
        public string region { get; set; }
        public Instancetype instanceTypes { get; set; }
    }

    public class Instancetype
    {
        public string type { get; set; }
        public Size sizes { get; set; }
    }

    public class Size
    {
        public string size { get; set; }
        public string vCPU { get; set; }
        public string ECU { get; set; }
        public string memoryGiB { get; set; }
        public string storageGB { get; set; }
        public Valuecolumn valueColumns { get; set; }
    }

    public class Valuecolumn
    {
        public string name { get; set; }
        public Prices prices { get; set; }
    }

    public class Prices
    {
        public string USD { get; set; }
    }



   private static T _download_serialized_json_data<T>(string url) where T : new() {
  using (var w = new WebClient()) {
    var json_data = string.Empty;
    // attempt to download JSON data as a string
    try {
      json_data = w.DownloadString(url);
    }
    catch (Exception) {}
    // if string with JSON data is not empty, deserialize it to class and return its instance 
    return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<T>(json_data) : new T();
  }
}

1 个答案:

答案 0 :(得分:2)

如果我从这里获取JSON并应用你的课程,

https://a0.awsstatic.com/pricing/1/deprecated/ec2/pricing-on-demand-instances.json

一般来说,问题似乎是在JSON中指定了一个值数组,但是你的类只需要一个键/值。

例如,对于您的配置类(我为了简洁而减少了JSON和类),JSON看起来像这样,

{
"vers": 0.01,
"config": {
    "rate": "perhr",
    "valueColumns": [
        "linux",
        "windows"
    ]
}
}

但你的班级看起来像这样,

public class Config
{
    public string rate { get; set; }
    public string valueColumns { get; set; }
}

所以你的valueColumns只期望一个值,而不是它们的数组。在JSON中,您可以看到它是一个数组,因为[]包含了值列的条目。如果您尝试反序列化,您将获得例如..:

等异常
Additional information: Error reading string. Unexpected token: StartArray. Path 'config.valueColumns', line 5, position 22.

基本上说,我看到阵列的开头,但我没想到会有一个。因此,为了解决这个问题,您只需将该属性更改为类中的数组,如下所示。

public class Config
{
    public string rate { get; set; }
    public string[] valueColumns { get; set; }
}