简体   繁体   中英

C# Json.Net - How to deserialize complex object Google Elevation

I have this JSON:

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

This class:

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; } 
}

This code:

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();
}

And this error:

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. 

where I went wrong?

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

You want "results" from the JSONObject. Use json.results

In the JSON, location is an object, not an array. However, in your Elevacao class location is defined as an array. They need to match in order for deserialization to work correctly. That is what the error message is trying to tell you.

To fix it, change this line:

public dados[] location { get; set; }                

To this:

public dados location { get; set; }                

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM