java 将 JSONObject 转换为 List<JSONObject> 或将字符串转换为 List<JSONObject>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31649495/
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
Convert JSONObject to List<JSONObject> or a String to List<JSONObject>
提问by Aishwarya Garg
I submit a query from my Java application, which upon running on Elasticsearch server returns the result in the form of a string. I want the result as a list of JSONObject
objects. I can convert the string to a JSONObject
using JSONObject jsonResponse = new JSONObject(responseString)
.
我从我的 Java 应用程序提交了一个查询,它在 Elasticsearch 服务器上运行时以字符串的形式返回结果。我想要结果作为JSONObject
对象列表。我可以将字符串转换为JSONObject
using JSONObject jsonResponse = new JSONObject(responseString)
。
Is there any method by which I can get this in the form of a List<JSONObject>
?
有什么方法可以让我以 a 的形式获得它List<JSONObject>
?
回答by Victor Dodon
Instead of using JSONObject you may use JSONArray. If you really need to convert it to a List you may do something like:
您可以使用JSONArray代替 JSONObject 。如果您确实需要将其转换为 List,您可以执行以下操作:
List<JSONObject> list = new ArrayList<JSONObject>();
try {
int i;
JSONArray array = new JSONArray(string);
for (i = 0; i < array.length(); i++)
list.add(array.getJSONObject(i);
} catch (JSONException e) {
System.out.println(e.getMessage());
}
回答by Vyacheslav
There is an answer of your question: https://stackoverflow.com/a/17037364/1979882
你的问题有答案:https: //stackoverflow.com/a/17037364/1979882
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
回答by itssaifurrehman
This method is really easy and works too
这个方法真的很简单,也很管用
try {
JSONObject jsonObject = new JSONObject(THESTRINGHERE);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonArray;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
// System.out.println(listdata);
} catch (Exception e) {
System.out.println(e.getMessage());
}