java SimpleJson:字符串到 JSONArray
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35622707/
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
SimpleJson: String to JSONArray
提问by mosquito87
I get the following JSON:
我得到以下 JSON:
[
{
"user_id": "someValue"
}
]
It's saved inside a String.
它保存在一个字符串中。
I would like to convert it to a JSONObject
which fails (as the constructor assumes a JSON to start with {
). As this doesn't seem to be possible I'd like to convert it to a JSONArray
. How can I do that with SimpleJson?
我想将其转换为JSONObject
失败的(因为构造函数假定以 JSON 开头{
)。由于这似乎不可能,我想将其转换为JSONArray
. 我怎么能用 SimpleJson 做到这一点?
回答by Michael Lloyd Lee mlk
JSONParser parser = new JSONParser();
JSONArray array = (JSONArray)parser.parse("[{\"user_id\": 1}]");
System.out.println(((JSONObject)array.get(0)).get("user_id"));
You need to cast to a JSONArray as that is what the string contains.
您需要转换为 JSONArray,因为这是字符串包含的内容。
回答by Solorad
For your task you could use code as bellow:
对于您的任务,您可以使用以下代码:
String t = "[{\"user_id\": \"someValue\"}]";
JSONParser parser = new JSONParser();
JSONArray obj = (JSONArray) parser.parse(t);
System.out.println(obj.get(0));
And result would be JSONObject.
结果将是 JSONObject。
回答by Vikrant Kashyap
String actualJsonObject = // assuming that this variable contains actual object what ever u want to pass as per your question says
JSONParser parser = new JSONParser();
JSONArray userdataArray= (JSONArray) parser.parse(actualJsonObject );
if(userdataArray.size()>0){
for (Object user : userdataArray) {
JSONObject jsonrow=(JSONObject)parser.parse(String.valueOf(user));
String User_Id= (String)jsonrow.get("user_Id"); \ Each User_Id will be displayed.
} else{
System.out.println("Empty Array....");
}
回答by svichkar
It works for me.
这个对我有用。
String jsonString = "[{\"user_id\": \"someValue\"}]";
JSONArray jsonArray = new JSONArray();
JSONParser parser = new JSONParser();
try {
jsonArray = (JSONArray) parser.parse(js);
} catch (ParseException e) {
e.printStackTrace();
}