【问题标题】:How to extract key:value from html如何从html中提取键:值
【发布时间】:2016-08-08 05:50:36
【问题描述】:

我有以下从 servlet 发送到索引页面的字符串数据。

{  "hits" : {"hits" : [ { "_source":{"ID":"123","Status":"false","Name":"ABC_123","Date":"2010-08-16T11:07:48"}    }, {      "_source":{"ID":"124","Status":"false","Name":"ABC_678","Date":"2010-08-16T12:00:12"}    }, {      "_source":{"ID":"125","Status":"true","Name":"FGH_122","Date":"2010-08-16T12:01:48"}    }, {      "_source":{"ID":"126","Status":"false","Name":"TYT_333","Date":"2010-08-16T12:06:48"}    }, {      "_source":{"ID":"127","Status":"false","Name":"CVF_230","Date":"2010-08-16T12:07:18"}    }, {      "_source":{"ID":"128","Status":"true","Name":"AWE_101","Date":"2010-08-16T12:03:48"}    }, {      "_source":{"ID":"129","Status":"true","Name":"WEC_299","Date":"2010-08-16T12:07:29"}    } ]  }}

我想解析数据并查看数组列表格式的数据,例如:

{ID:"123", "Name":"ABC_123"}
{ID:"124", "Name":"ABC_678"}

等等……

关于如何从客户端或服务器实现这一点的任何想法?请指教..谢谢

【问题讨论】:

标签: java html json jsp servlets


【解决方案1】:

创建一个新数组并向其中添加对象,然后再将它们返回给 JSP。

JSONArray arr = new JSONArray();
for (int i = 0 ; i < hitsArray.length(); i++) {
    JSONObject jObject = hitsArray.getJSONObject(i);
    arr.put(jObject.get("_source"));         
}    

request.setAttribute("jsonObject", arr);
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request, response);

【讨论】:

    【解决方案2】:

    您应该在循环之前创建一个HashMaps 的ArrayList,并在那里添加数据。 像这样

    ...rest of your code...
    List<Map<String, String>> list = new ArrayList<Map<String, String>>();            
    for (int i = 0 ; i < hitsArray.length(); i++) {
        JSONObject jObject = hitsArray.getJSONObject(i);
        Map<String, String> data = new HashMap<String, String>();
        JSONObject source = jObject.get("_source");
        Iterator<String> it = source.keys();
        while (it.hasNext()) {
            String key = it.next();
            data.put(key, source.getString(key));
        }
        list.add(data);
    }
    request.setAttribute("jsonObject", list);
    ... rest of your code...
    

    更新了抛弃的代码,但我建议切换到 javax.json;

    【讨论】:

    • 你能告诉我“....将数据从_source复制到数据映射...”是什么意思吗?谢谢。
    • 我得到“构造函数 HashMap(Object) 未定义”
    • 什么是JSONObject?你用的是哪个库?如果您使用 JEE 中的JsonObject,它会起作用。
    • 我正在使用“import org.codehaus.jettison.json.JSONObject;”
    • 感谢您的帮助。不幸的是,我仍然遇到一些错误。 Roman的代码有效。感谢您的宝贵时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 2018-06-11
    • 1970-01-01
    • 2020-08-07
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多