2016-05-15 68 views
-3

我叫API返回一個JSON字符串,像這樣的一個:獲取響應由網絡API JSON字符串並打印值

{ 
    "type": "success", 
    "value": 
    { 
     "id": 246, 
     "joke": "Random joke here...", 
     "categories": [] 
    } 
} 

我想我的程序讀取JSON字符串,返回只有joke字符串。我能夠從Web API獲取字符串,但是我無法將其傳遞給JSON對象,因此我只能打印笑話字符串。

+1

你可以只是使用佔位符而不是真正的笑話,因爲你在這樣的問答網絡上發佈代碼...... –

+0

@FᴀʀʜᴀɴAɴᴀᴍ你在編輯這個笑話時是正確的。海報鏈接到一個笑話api,返回隨機笑話 – Nkosi

回答

1

首先你需要創建類來反序列化你的json。爲此,您可以使用VS的編輯 - >選擇性粘貼 - >粘貼JSON作爲類或使用一個網站就像JsonUtils

public class JokeInfo 
{ 

    [JsonProperty("id")] 
    public int Id { get; set; } 

    [JsonProperty("joke")] 
    public string Joke { get; set; } 

    [JsonProperty("categories")] 
    public IList<string> Categories { get; set; } 
} 

public class ServerResponse 
{ 

    [JsonProperty("type")] 
    public string Type { get; set; } 

    [JsonProperty("value")] 
    public JokeInfo JokeInfo { get; set; } 
} 

然後使用庫像JSON.NET反序列化數據:

// jokeJsonString is the response you get from the server 
var serverResponse = JsonConvert.DeserializeObject<ServerResponse>(jokeJsonString); 
// Then you can access the content like this: 

var theJoke = serverResponse.JokeInfo.Joke; 
+2

非常感謝你說實話,json需要的類是我的問題,現在你粘貼這個網站,我認爲我很好! –