简体   繁体   English

使用GSON解析JSON格式?

[英]parse JSON format using GSON?

With HTTPURLCONNECTION I am able to get the JSON response and using Writer I am able to save it to output.json file also. 使用HTTPURLCONNECTION,我可以获得JSON响应,并且使用Writer,也可以将其保存到output.json文件。 But I am not able to read the content of output.json or directly from the url " http://somesite.com/json/server.json " using GSON. 但是我无法使用GSON来读取output.json的内容或直接从URL“ http://somesite.com/json/server.json ”中读取内容。 I am facing few issues when using gson. 使用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();
        }
    }

}

The other class I am passing during gson.fromjson call is Jsondata. 我在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 ;
    }
}

Outputs: 输出:

Json format (Is the JSON format looks fine or any syntax error is there in it) 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":[]}

Value printed for variable p is null. 为变量p打印的值为空。

Could some one please help me in printing the Json response in variable p using Gson. 有人可以帮我使用Gson在变量p中打印Json响应。

Wait until you've read the entire response body before you try and convert it with GSON. 等待直到您阅读了整个响应正文,然后再尝试使用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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM