提取JSON值

时间:2014-11-04 00:30:50

标签: java json servlets

我在尝试从JSON中提取值时遇到了一些问题。这是从我的servlet返回的JSON:

[
    {
        "eventDesc":"My sons 5th year birthday party",
        "eventDate":"12/11/2014",
        "eventID":"1",
        "eventName":"Birthday party",
        "eventTime":"17:00",
        "eventX":"41803.2",
        "eventY":"38210.8",
        "eventBy":"Gabriel"
    },
    {
        "eventDesc":"Steamboat Gathering",
        "eventDate":"20/11/2014",
        "eventID":"2",
        "eventName":"Gathering",
        "eventTime":"19:00",
        "eventX":"41551.6",
        "eventY":"38211.7",
        "eventBy":"JunHong"
    }
]

而且我不知道我应该如何提取每条记录的记录,因为我必须将每条记录都绘制到地图上。

我有这些代码要从servlet中返回的JSON中提取:

public void getThemesOnMap() throws JSONException{
    String page;
    BufferedReader in;
    JSONArray jsonArray;

    try{
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet("http://localhost:8080/MyProject/MyServlet");
        HttpResponse response = client.execute(request);

        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while((line = in.readLine()) != null){
            sb.append(line + NL);
        }
        in.close();
        page = sb.toString();
        System.out.println(page);
        try{
            JSONObject jsonObject = new JSONObject(page);
            jsonArray = jsonObject.getJSONArray(page);
            int length = jsonArray.length();
            for(int i = 1; i < length; i++){
                JSONObject attribute = jsonArray.getJSONObject(i);
                String eventName = attribute.getString("eventName");
                String eventX = attribute.getString("eventX");
                String eventY = attribute.getString("eventY");

                PictureMarkerSymbol graphicIcon;
                graphicIcon = new PictureMarkerSymbol(this.getResources().getDrawable(R.drawable.busstopicon));
                Point p = new Point(Double.parseDouble(eventX), Double.parseDouble(eventY));
                Symbol symbol = graphicIcon;

                HashMap<String, Object> attrMap = new HashMap<String, Object>();
                attrMap.put("eventName", eventName);

                graphicsLayer.addGraphic(new Graphic(p, symbol, attrMap));
            }
        }
        catch(JSONException e){
            e.printStackTrace();
        }
    }
    catch(IOException e){
        e.printStackTrace();
    }
}

但它不会在地图上绘制任何内容。有什么想法吗?

提前致谢。

修改

我如何格式化我的JSON以返回:

{Events:[
{
    "eventDesc":"My sons 5th year birthday party",
    "eventDate":"12/11/2014",
    "eventID":"1",
    "eventName":"Birthday party",
    "eventTime":"17:00",
    "eventX":"41803.2",
    "eventY":"38210.8",
    "eventBy":"Gabriel"
},
{
    "eventDesc":"Steamboat Gathering",
    "eventDate":"20/11/2014",
    "eventID":"2",
    "eventName":"Gathering",
    "eventTime":"19:00",
    "eventX":"41551.6",
    "eventY":"38211.7",
    "eventBy":"JunHong"
}]
}

这是我从数据库中检索数据的servlet方法:

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    if(request.getParameter("SQL1")!=null){

    }

    JSONArray jsonArray = new JSONArray();
    PrintWriter out = response.getWriter();
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost/mydb", "root", "root");

        PreparedStatement statement = con
                .prepareStatement("SELECT * FROM event");
        ResultSet result = statement.executeQuery();
        while (result.next()) {
            JSONObject eventInfo = new JSONObject();
            eventInfo.put("eventID", result.getString("eventID"));
            eventInfo.put("eventName", result.getString("eventName"));
            eventInfo.put("eventDesc", result.getString("eventDesc"));
            eventInfo.put("eventDate", result.getString("eventDate"));
            eventInfo.put("eventTime", result.getString("eventTime"));
            eventInfo.put("eventX", result.getString("eventX"));
            eventInfo.put("eventY", result.getString("eventY"));
            eventInfo.put("eventBy", result.getString("eventBy"));
            jsonArray.put(eventInfo);
        }
    }

    catch (JSONException je) {
        System.out.println(je.getMessage());
    } catch (Exception exc) {
        System.out.println(exc.getMessage());
    }

    out.println(jsonArray.toString());
}

3 个答案:

答案 0 :(得分:0)

创建JSONArray

JSONArray arr = new JSONArray("your json string here");

浏览

for (int i = 0; i < arr.length; i++)
{
    JSONObject o = arr.getJSONObject(i);
     //...

此处提供更多信息:http://www.json.org/javadoc/index.html?org/json/JSONObject.html

修改

这样做:

jsonArray = new JSONArray(page);
int length = jsonArray.length();
for(int i = 0; i < length; i++){
    //...

<强> EDIT2

要获得所需的JSON,请执行以下操作:

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    if(request.getParameter("SQL1")!=null){

    }

    JSONObject result = new JSONObject();
    JSONArray jsonArray = new JSONArray();
    PrintWriter out = response.getWriter();
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost/mydb", "root", "root");

        PreparedStatement statement = con
                .prepareStatement("SELECT * FROM event");
        ResultSet result = statement.executeQuery();
        while (result.next()) {
            JSONObject eventInfo = new JSONObject();
            eventInfo.put("eventID", result.getString("eventID"));
            eventInfo.put("eventName", result.getString("eventName"));
            eventInfo.put("eventDesc", result.getString("eventDesc"));
            eventInfo.put("eventDate", result.getString("eventDate"));
            eventInfo.put("eventTime", result.getString("eventTime"));
            eventInfo.put("eventX", result.getString("eventX"));
            eventInfo.put("eventY", result.getString("eventY"));
            eventInfo.put("eventBy", result.getString("eventBy"));
            jsonArray.put(eventInfo);
        }
        result.put("Events", (Object) jsonArray);
    }

    catch (JSONException je) {
        System.out.println(je.getMessage());
    } catch (Exception exc) {
        System.out.println(exc.getMessage());
    }

    out.println(result.toString());
}

答案 1 :(得分:0)

如果你想映射json,你可能想要使用现有的javascript / jquery库 但是你要知道我假设你想要创建一个时间轴地图,所以算法在这里:

you need to loop over dates check any event from this date from you json by looping through it if there are events then put it to the map horizontally then start the next loop to check.

希望有所帮助

答案 2 :(得分:0)

您是否考虑过使用Spring框架的RestTemplate类? 它直接结合了http请求,可以将JSON回复映射到大约5行代码中的pojo。优点是您知道映射工作正常,源代码更易读。

帮助我很多的例子:https://spring.io/guides/gs/consuming-rest/