SimpleJson: string for JSONArray

I get the following JSON:

[ { "user_id": "someValue" } ] 

It is stored inside the string.

I would like to convert it to a JSONObject that does not work (since the constructor assumes JSON starts with { ). Since this is not possible, I would like to convert it to a JSONArray . How can I do this using SimpleJson?

+5
source share
4 answers
 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 send to JSONArray as this is what the string contains.

+3
source

For your task, you can use the code below:

 String t = "[{\"user_id\": \"someValue\"}]"; JSONParser parser = new JSONParser(); JSONArray obj = (JSONArray) parser.parse(t); System.out.println(obj.get(0)); 

And the result will be JSONObject.

+1
source
 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...."); } 
0
source

This 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(); } 
0
source

Source: https://habr.com/ru/post/1243825/


All Articles