2013-10-24 94 views
1

我有這樣的JSON:C#Json.Net - 如何反序列化複雜對象谷歌海拔

{ 
    "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. 

我哪裏出錯了?

+1

您mispasted您的錯誤。 – SLaks

+0

我認爲不是錯誤,你打印你的行動結果兩次 –

+1

你不明白什麼部分的明確和非常詳細的錯誤信息? – SLaks

回答

1

在JSON中,location是一個對象,而不是數組。但是,在您的Elevacaolocation被定義爲一個數組。它們需要匹配才能使反序列化正確工作。這是錯誤信息試圖告訴你的。

要修復它,改變這一行:

public dados[] location { get; set; }     

要這樣:

public dados location { get; set; }     
1

location在你的JSON中是一個單一的對象,而不是一個數組。

+0

如何解決該問題? @SLaks –

+0

@ marlon.tiedt:將類中的屬性更改爲不是數組。 – SLaks

1

你想要JSONObject的「結果」。使用json.results