【问题标题】:Get response by web api a json string and print only one of the values通过 web api 获取响应一个 json 字符串并仅打印其中一个值
【发布时间】:2016-09-11 10:13:41
【问题描述】:

我调用了一个API,它返回一个像这样的 JSON 字符串:

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

我想让我的程序读取 JSON 字符串并仅返回 joke 字符串。我能够从 Web API 获取字符串,但无法将其转换为 JSON 对象,因此我只能打印笑话字符串。

【问题讨论】:

  • 您可以只使用占位符而不是真正的笑话,因为您在这样的问答网络上发布代码......
  • @FᴀʀʜᴀɴAɴᴀᴍ 你在编辑这个笑话时是正确的。海报链接到一个返回随机笑话的笑话 api

标签: c# json asp.net-web-api json-deserialization


【解决方案1】:

首先,您需要创建类以将您的 json 反序列化为。为此,您可以使用 VS 的 Edit -> Paste Special -> Paste Json As Classes 或使用 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;

【讨论】:

  • 非常感谢你说实话,json 需要的类是我的问题,因为你粘贴了这个网站,我认为我很好!
猜你喜欢
  • 2021-12-22
  • 1970-01-01
  • 2020-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-08
  • 2017-03-31
  • 1970-01-01
相关资源
最近更新 更多