-2

Input Json String: "{"predicted_route": [1, 351, 371, 372, 373, 0]}" that has been received after making a Post Request call to a backend server.

I would like to extract the List from the JSON String into an ArrayList.

I haven't found anything online that shows how one would go about this?

If I can use org.json that would be the best.

Thanks

2 Answers2

2
import org.json.*;

String jsonString = inputJsonString; //assign your JSON String here
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("predicted_route");
ArrayList<String> arrayList = new ArrayList<String>(); 
if (jsonArray != null) { 
    for (int i = 0; i < jsonArray.length(); i++) { 
        arrayList.add(jsonArray.getString(i));
    } 
} 

More examples to parse JSON in Java

Downloadable jar: http://mvnrepository.com/artifact/org.json/json

Aditya Jain
  • 153
  • 1
  • 9
1

Include Jackson dependency so you're able to deserialize the JSON without parsing it manually

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.4</version>
</dependency>

Create a POJO representation of your object. To have predicted_route mapped to the correct field you can annotate it with @JsonProperty.

class Route {  
  
    @JsonProperty("predicted_route")
    private List<Integer> predictedRoute;  
    
    public List<Integer> getPredictedRoute(){
        return predictedRoute;
    }
    
    public void setPlannedRoute(List<Integer> route){
        this.plannedRoute = route;
    }
}

Map the JSON string to your object

String yourJson = "{\\"predicted_route\\": [1, 351, 371, 372, 373, 0]}";
Route myRoute = new ObjectMapper().readValue(yourJson, Route.class);

System.out.println(myRoute.getPredictedRoute());
Dropout
  • 13,653
  • 10
  • 56
  • 109