【问题标题】:C# Json.Net - How to deserialize complex object Google ElevationC# Json.Net - 如何反序列化复杂对象 Google Elevation
【发布时间】:2013-10-24 17:25:08
【问题描述】:

我有这个 JSON:

{
   "results" : [
      {
         "elevation" : 25.51896667480469,
         "location" : {
            "lat" : -26.90408425509977,
            "lng" : -49.04650926589966
         },
         "resolution" : 152.7032318115234
      }
   ],
   "status" : "OK"
}

这个类:

public class RootObject
{
    public Elevacao[] results { get; set; }
    public string status { get; set; }
}


public class Elevacao
{
    public Decimal elevation { get; set; }
    public Decimal resolution { get; set; }
    public dados[] location { get; set; }                
}

public class dados
{
    public Decimal lat { get; set; }
    public Decimal lng { get; set; } 
}

这段代码:

public ActionResult Teste()
{
    var url = "http://maps.googleapis.com/maps/api/elevation/json?locations=-26.904084255099768,-49.04650926589966&sensor=false&format=json";
    var json = new WebClient().DownloadString(url);

    RootObject m = JsonConvert.DeserializeObject<RootObject>(json);

    return View();
}

还有这个错误:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'TCC.Controllers.dados[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'results[0].location.lat', line 6, position 20. 

我哪里出错了?

【问题讨论】:

  • 你贴错了错误。
  • 我认为您打印了两次操作结果而不是错误
  • 清晰且极其详细的错误消息的哪一部分你不明白?

标签: c# json serialization json.net deserialization


【解决方案1】:

在 JSON 中,location 是一个对象,而不是一个数组。但是,在您的 Elevacao 类中,location 被定义为一个数组。它们需要匹配才能使反序列化正常工作。这就是错误消息试图告诉您的内容。

要修复它,请更改此行:

public dados[] location { get; set; }                

到这里:

public dados location { get; set; }                

【讨论】:

    【解决方案2】:

    您的 JSON 中的location 是单个对象,而不是数组。

    【讨论】:

    • 我该如何解决这个问题? @SLaks
    • @marlon.tiedt:将类中的属性更改为不是数组。
    【解决方案3】:

    您想要来自 JSONObject 的“结果”。使用json.results

    【讨论】:

      猜你喜欢
      • 2014-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      • 2018-10-27
      • 1970-01-01
      相关资源
      最近更新 更多