Home » Java » java – How can i use replace in JSON?-Exceptionshub

java – How can i use replace in JSON?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

Heyy,

I have a JSON String i.e.

{"userId":"WaNenOnQt","photos":[{"photo_url":"vendor_photos/WaNenOnQt/web_(138)(4thcopy).JPG","index":1},{"photo_url":"vendor_photos/WaNenOnQt/54230451_265006064447640_7942942433146217157_n.jpg","index":2}]}

I want only the List data i.e. –

[{"photo_url":"vendor_photos/WaNenOnQt/web_(138)(4thcopy).JPG","index":1},{"photo_url":"vendor_photos/WaNenOnQt/54230451_265006064447640_7942942433146217157_n.jpg","index":2}]

Is there any replace function in java or how can i segregate the list ?

How to&Answers:

assuming you are getting that JSON through an endpoint you are exposing, you should bind it to the method signature, for example if you are using Spring:


public class MyPojo {
    private String userId;
    private List<Photo> photoList;
    //getters & setters
}

Photo class

public class Photo {
    @JsonProperty("photo_url")
    private String url;
    private int index;
    //getters & setters
}

Controller class

@RequestMapping(value = "/test", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> test(@RequestBody MyPojo request) {
    List<Photo> photos = request.getPhotoList();
}

Alternatively if you don’t have an endpoint, you can manually transform the JSON String to a POJO and vice-versa, using Java’s ObjectMapper. For example:

public void transform(String jsonString) throws... {
    ObjectMapper mapper = new ObjectMapper();
    MyPojo pojo = mapper.readValue(jsonString, MyPojo.class);
    List<Photo> photo = pojo.getPhotoList();
}

I’m also assuming that you need a Java List, and don’t need the JSON array simply as a String.