Java 将 JSON OBJECT 转换为 JSON ARRAY
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44046413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
converting JSON OBJECT to JSON ARRAY
提问by user6250770
This is very simple one but struggeling. help me out of this.
这是一个非常简单但很挣扎的方法。帮我解决这个问题。
I am having a json data { "abc":"test","bed":"cot","help":"me"}
我有一个 json 数据 { "abc":"test","bed":"cot","help":"me"}
I want to convert above jsonObject into JSON ARRAY like [{ "abc":"test","bed":"cot","help":"me"}]
我想将上面的 jsonObject 转换为 JSON ARRAY 像 [{ "abc":"test","bed":"cot","help":"me"}]
JSONObject obj= new JSONObject(str.toString());
Iterator x = obj.keys();
JSONArray jsonArray = new JSONArray();
Map<String, String> map = new HashMap<String, String>();
while (x.hasNext()) {
for(int i=0;i<obj.length();i++) {
LOG.info("=============");
String key = (String) x.next();
jsonArray.put(obj.get(key));
}
}
I am getting only values. Please help me solve this.
我只得到值。请帮我解决这个问题。
采纳答案by Pehlaj
Directly put JsonObject i.e. obj into jsonArray
直接把JsonObject即obj放入jsonArray
jsonArray.put(obj);
//result is [{ "abc":"test","bed":"cot","help":"me"}]
Final code
最终代码
JSONObject obj= new JSONObject(str);
JSONArray jsonArray = new JSONArray();
//simply put obj into jsonArray
jsonArray.put(obj);
//result is [{ "abc":"test","bed":"cot","help":"me"}]
回答by Avinash Kumar
It works for me.
这个对我有用。
JSONObject obj = new JSONObject(result.toString()); JSONArray arr = obj.getJSONArray("value");
JSONObject obj = new JSONObject(result.toString()); JSONArray arr = obj.getJSONArray("value");