【问题标题】:How do I use Google's Gson to get a certain value from a JSON response?如何使用 Google 的 Gson 从 JSON 响应中获取特定值?
【发布时间】:2013-05-12 01:15:33
【问题描述】:

我目前正在尝试使用他们很酷的网站功能解析 Reddit 的首页,您可以在其中将 /.json 添加到任何站点以获取页面的 json。所以我使用的网址是 www.reddit.com/.json。

我想通过解析他们的 json 来获取第一篇文章的 subreddit。我该怎么做?我做了一些研究并找到了 google gson api,但我不知道如何使用它,他们的文档并没有真正帮助我。

到目前为止,这是我的代码,我有一个字符串中的 Json:

import java.io.*;
import java.net.*;
import com.google.gson.*;

public class Subreddits {

public static void main(String[] args) {
    URL u = null;
    try {
        u = new URL("http://www.reddit.com/.json");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    URLConnection yc = null;
    try {
        yc = u.openConnection();
    } catch (IOException e) {
        e.printStackTrace();
    }
    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
    } catch (IOException e) {
        e.printStackTrace();
    }
    String inputLine = null;
    StringBuilder sb = new StringBuilder();
    try {
        while ((inputLine = in.readLine()) != null){
            sb.append(inputLine);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    inputLine = sb.toString();//String of json
    System.out.println(inputLine);
    //I want to get [data][children][data][subreddit]
}

}

【问题讨论】:

    标签: java json gson


    【解决方案1】:

    你可以创建这个类结构来解析你的响应(在伪代码中):

    class Response
      Data data
    
    class Data
      List<Child> children
    
    class Child
      OtherData data
    
    class OtherData
      String subreddit
    

    然后你解析你的 JSON 字符串:

    Gson gson = new Gson();
    Response response = gson.fromJson(inputLine, Response.class);
    

    为了获得您需要的具体数据,只需:

    String subreddit = response.getData().getChildren().getOtherData().getSubreddit();
    

    请注意,您可以更改类的名称,但不能更改属性的名称,因为它们必须与 JSON 响应中的名称匹配!

    另外请注意,我只添加了获取具体数据所需的属性,但如果您在类中添加更多属性,匹配 JSON 中的元素名称,将解析更多数据...

    更多类似示例hereherehere

    最后请注意,您可以使您的类嵌套以使您的项目更整洁,但是如果您不喜欢编写这么多的类,并且您确定您只想要那个特定的值并且您不会想要任何以后value else,可以用this different approach,虽然我不推荐...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多