使用GSON解析JSON格式?

时间:2015-01-14 05:00:34

标签: java json gson httpurlconnection

使用HTTPURLCONNECTION我能够获得JSON响应并使用Writer我也可以将它保存到output.json文件中。但是我无法使用GSON直接从URL“http://somesite.com/json/server.json”读取output.json的内容。使用gson时我遇到的问题很少。

public class ConnectToUrlUsingBasicAuthentication {

    public static void main(String[] args) {

        try {
            String webPage = "http://somesite.com/json/server.json";
            //HTTPURLCONNECTION
            URL url = new URL(webPage);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            StringBuilder sb = new StringBuilder();
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is,Charset.defaultCharset());
            BufferedReader bufferedReader = new BufferedReader(isr);
            String line;
            while((line = bufferedReader.readLine()) != null) {
                System.out.println("*** BEGIN ***");
                try(Writer writer = new OutputStreamWriter(new FileOutputStream("Output.json") , "UTF-8")){
                    Gson gson = new GsonBuilder().create();
                    gson.toJson(line, writer);
                    System.out.println("Written successfully");
                }
                System.out.println(line);
                System.out.println("*** END ***");
                try(Reader reader = new InputStreamReader(is, "UTF-8")){
                    Gson gson = new GsonBuilder().create();
                    JsonData p = gson.fromJson(reader, JsonData.class);
                    System.out.println(p);
                }
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

我在gson.fromjson调用期间传递的另一个类是Jsondata。

public class JsonData {
    private String body;
    private List<String> items = new ArrayList<String>();
    private List<String> messages = new ArrayList<String>();

    // Getters and setters are not required for this example.
    // GSON sets the fields directly using reflection.

    @Override
    public String toString() {
        return messages + " - " + items + " - " + messages ;
    }
}

输出:

Json格式(JSON格式是否正常或其中存在任何语法错误)

line = {
    "body":
        {"items":[
            {"name":"server","state":"RUNNING","health":"HEALTH_OK"},
            {"name":"server1","state":"RUNNING","health":"HEALTH_OK"},
            {"name":"server2","state":"RUNNING","health":"HEALTH_OK"}
        ]},

    "messages":[]}

为变量p打印的值为null。

有人可以帮我用Gson打印变量p中的Json响应。

1 个答案:

答案 0 :(得分:0)

在尝试使用GSON进行转换之前,请等待您阅读整个响应正文。

try (Writer writer = new OutputStreamWriter(
        new FileOutputStream("Output.json") , "UTF-8")) {
    Gson gson = new GsonBuilder().create();
    while((line = bufferedReader.readLine()) != null) {
         gson.toJson(line, writer);
    }
}
// Now read it.
try (Reader reader = new InputStreamReader(is, "UTF-8")){
    Gson gson = new GsonBuilder().create();
    JsonData p = gson.fromJson(reader, JsonData.class);
    System.out.println(p);
}