要在其中單獨的html_attributions和next_page_token我不理解的部分。
只需反序列化您需要的任何屬性即可嗎?
例如,您可以反序列化響應以僅檢索您想要的值;
// I represent the wrapper result
class Result
{
public List<string> html_attributions { get; set; }
public string next_page_token { get; set; }
public List<ResultItem> results { get; set; }
}
// I represent a result item
class ResultItem
{
public string id { get; set; }
public string name { get; set; }
}
// the actual deserialization
Result Deserialize(string json)
{
var serializer = new JavaScriptSerializer();
return serializer.Deserialize(json, typeof(Result));
}
編輯: 你的反序列化不回你的字符串的數組的原因是因爲您檢索到的響應是逸岸的對象,而不是一個數組,但是這個對象是一個名爲結果中的參數是一個數組。爲了讓你反序列化更多的屬性,你必須在你的「ResultItem」類中定義它們,對不起,我的糟糕的命名在這裏。例如,如果您還希望爲每個結果檢索圖標屬性,則必須添加名爲「icon」的屬性類型爲string的屬性。
同時,屬性「photos」是一個數組,爲了反序列化它,您將不得不創建另一個類並添加該類新建類的list/array屬性,並且必須命名爲「photos 「除非您使用不同的序列化程序或使用DataContract和DataMember屬性(使用Name屬性進行字段映射)。
// the representation of a photo within a result item
class Photo
{
public int height { get; set; }
public List<string> html_attributions { get; set; }
public string photo_reference { get; set; }
public int width { get; set; }
}
// I represent a result item
class ResultItem
{
public string id { get; set; }
public string name { get; set; }
// the added icon
public string icon { get; set; }
// the added photos collection, could also be an array
public List<Photo> photos { get; set; }
}
試想一下,在JSON結果弄清楚,你可能要添加什麼其他的屬性,比如「範圍」屬性是一個字符串,而「PRICE_LEVEL」是一個整數。
如果我正確理解了你的評論,你只對實際結果感興趣,你仍然需要用它的包裝器正確地反序列化響應。
// the actual deserialization
List<ResultItem> Deserialize(string json)
{
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize(json, typeof(Result));
return result.results;
}
EDIT2: 如果你真的想要一個字符串[]作爲一個結果,你可以簡單地使用上面的代碼使用採取的System.Linq的。
string[] stringArray = result.results.Select(r => string.Format("id:{0} - name:{1}", r.id, r.name)).ToArray();
EDIT3: 而不是使用JavascriptSerializer你可以使用JObject功能可在Newtonsoft.Json.Linq庫中找到的。
var jsonObject = JObject.Parse(json);
string[] results = jsonObject.SelectTokens("results").Select(r => r.ToString()).ToArray();
這會給你一個字符串數組,其中每個數組中的每個值都是每個結果的實際json字符串。
不過,若你想查詢只有座標:
var jsonObject = JObject.Parse(json);
var coordinates = jsonObject["results"]
.Select(x => x.SelectToken("geometry").SelectToken("location"))
.Select(x => string.Format("{0},{1}", (string)x.SelectToken("lat"), (string)x.SelectToken("lng")))
.ToArray();
這會給你座標的數組,例如:
[
"-33.867217,151.195939",
"-33.866786,151.195633",
...
]
無論您選擇哪種方法,你就可以使用Newtonsoft或.net序列化程序來完成相同的結果,而Newtonsoft方法將允許您在不爲反序列化創建強類型的情況下進行查詢。
這幾乎是我所需要的,只是最後一件事,現在我有一個包含所有這個值的對象,但是如何將這個'object'轉換成'List'的'string []'? – Maven
我想做'string [] arr = result.results;'但我不能因爲我得到'不能隱式轉換類型'System.Collections.Generic.List'到'string [] ' –
Maven
再次編輯,但我不明白爲什麼你想要反序列化的反應,如果你只是打算作爲字符串值的工作。也許你應該看看Newtonsoft或任何其他允許你查詢json對象的庫。 – Olivier