我如何使用Google的Gson从JSON响应中获得特定的值? [英] How do I use Google's Gson to get a certain value from a JSON response?

查看:206
本文介绍了我如何使用Google的Gson从JSON响应中获得特定的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想通过解析他们的json来获得第一篇文章的subreddit。我将如何做到这一点?我做了一些研究,发现了google gson api,但是我不知道如何使用它,他们的文档并没有真正帮助我。



到目前为止,我有一个字符串Json:

  import java.io. *; 
导入java.net。*;
import com.google.gson。*;

public class Subreddits {

public static void main(String [] args){
URL u = null;
尝试{
u =新网址(http://www.reddit.com/.json);
} catch(MalformedURLException e){
e.printStackTrace();
}
URLConnection yc = null;
尝试{
yc = u.openConnection();
} catch(IOException e){
e.printStackTrace();
}
BufferedReader in = null;
尝试{
in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
} catch(IOException e){
e.printStackTrace();
}
String inputLine = null;
StringBuilder sb = new StringBuilder(); ((inputLine = in.readLine())!= null){
sb.append(inputLine);
尝试{
while
}
} catch(IOException e){
e.printStackTrace();
}
尝试{
in.close();
} catch(IOException e){
e.printStackTrace();
}
inputLine = sb.toString(); // JSON字符串
System.out.println(inputLine);
//我想获取[data] [children] [data] [subreddit]
}

}

解决方案

您可以创建此类结构来解析您的响应(在伪代码

  class响应
数据数据

类数据
列表< Child> children

class Child
其他数据数据

类OtherData
字符串subreddit

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

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

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

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

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



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

更多类似的例子 此处 此处 here



最后请注意,您可以让您的类嵌套以保持项目更清洁,但如果你不喜欢写这么多的类,并且你确定你只想要这个特定的值,而且你将来不需要任何其他值,你可以使用 这种不同的方法 ,尽管我不推荐它......


I am currently trying to parse through a the front page of Reddit using their cool website feature in which you can add /.json to any site to get the json of the page. So the url I am using is www.reddit.com/.json.

I want to get the subreddit of the first post by parsing through their json. How would I do this? I did some research and found the google gson api but I have no idea how to use it and their documentation does not really help me.

Here is my code so far, I have the Json in a string:

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]
}

}

解决方案

You can create this class structure to parse your response (in pseudo-code):

class Response
  Data data

class Data
  List<Child> children

class Child
  OtherData data

class OtherData
  String subreddit

Then you parse your JSON string with:

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

And in order to get the concrete data you need, just:

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

Note that you can change the names of the classes, but NOT the names of the attributes, since they have to match the names in the JSON response!

Also note that I have only added the attributes you need to get that concrete data, but if you add more attributes in the classes, matching the element names in the JSON, more data will be parsed...

Further similar examples here, here or here.

Finally note that you can make your classes nested to keep your project cleaner, but if however you don't like to write so many classes, and you are sure that you only want that specific value and you won't want any value else in the future, you can use this different approach, although I don't recommend it...

这篇关于我如何使用Google的Gson从JSON响应中获得特定的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆