JSON数据未打印出来

时间:2019-08-15 06:29:53

标签: java json

我在打印JSON数据时遇到了一些麻烦,而且我似乎无法弄清楚自己做错了什么。 out.pring(test)似乎可以打印出来。但是,out.println(val.getJsonString(“ country”));似乎什么也没打印出来。我从URL访问JSON,我想将这些数据解析为HTML表并打印出来。在创建表之前,我想检查我是否实际上正在获取数据。事实证明,数据无法打印,我似乎无法找出为什么此行不打印任何内容。

out.println(val.getJsonString("country"))

完整代码:

import java.net.*;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
import javax.json.*;


public class StatesServlet extends HttpServlet {
    public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {

        PrintWriter out = res.getWriter();
    try{
        String url="http://test.com/all.json";
            URL server = new URL(url);
            URLConnection connection = server.openConnection();
            InputStream file_in = connection.getInputStream();
            BufferedReader buffered = new BufferedReader(new InputStreamReader(file_in));
            StringBuilder test = new StringBuilder();
            String line ="";

            while((line = buffered.readLine())!= null){
                test.append(line+"\n");


            }
            buffered.close();
            out.println(test);

        JsonReader reader = Json.createReader(new StringReader(test.toString()));
            JsonObject jObject = reader.readObject();
            reader.close();
            JsonArray result = jObject.getJsonObject("RestResponse").getJsonArray("result");
            for (JsonObject val : result.getValuesAs(JsonObject.class)) {

        out.println(val.getJsonString("country"));


            }


        }catch(Exception e){
            e.printStackTrace();
        }



    }
}

json如下:

{
"RestResponse": {
	"messages": ["test", "test"],
	"result": [{
		"country": "test",
		"name": "test",
		"largest_city": "test ",
		"capital": "test"
	}, {
		"country": "test",
		"name": "test",
		"largest_city": "test ",
		"capital": "test"

	}]
}
}

0 个答案:

没有答案