2016-05-15 48 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需要的类是我的问题,现在你粘贴这个网站,我认为我很好! –