Gergely Kudó
Gergely Kudó

Reputation: 69

How to return proper JSON in JAVA

 private List<String> itemsInCart = new ArrayList<>();
 private List<String> itemObjectsInCart = new ArrayList<>();

@CrossOrigin
@GetMapping(value = "/cartitems")
public List<String> getItemsInCart(@RequestParam("buyerId") Integer buyerId) {
    if (cartRepository.findByBuyerIdAndIsCompleted(buyerId, false) != null){
        return getItemObjects(cartRepository.findByBuyerIdAndIsCompleted(buyerId, false).getItemsInCart());
    } else {
        return itemsInCart;
    }
}

public List<String> getItemObjects(List<String> itemsInCart){
    for (String item: itemsInCart) {
        String uri = "http://192.168.160.182:8762/item-service/items/" + item;
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(uri, String.class);
        JSONObject jsonObject = new JSONObject(result);
        System.out.println(jsonObject);
        if(itemObjectsInCart.contains(result)){
            return itemObjectsInCart;
        } else {
            itemObjectsInCart.add(result);
        }
    }
return itemObjectsInCart;
}

Hi guys! My code above returns a JSON in this format:

["{\"id\":1,\"name\":\"Stick\",\"description\":\"A stick\",\"price\":100,\"available\":true,\"img\":\"https://vignette.wikia.nocookie.net/tokipona/images/a/aa/Stick.png/revision/latest?cb=20171120043817\",\"uploadDate\":\"2019-01-16\",\"sellerId\":1}"]

But I would like it whithout backslashes. Do you have any idea how could I convert it to a proper JSON array?

Thanks in advance!

Upvotes: 1

Views: 3014

Answers (2)

Karol Dowbecki
Karol Dowbecki

Reputation: 44932

Don't use JSONObject to map to JSON and don't read String directly. Create new POJO class for the response and let RestTemplate do the work. Internally Spring will use suitable converter to map the objects:

public class Item {
  int id;
  String name;
  String description;
  // other fields
  // getters and setters
}

Item result = restTemplate.getForObject(uri, Item.class);

Your controller method should also return Item and not String:

@GetMapping"/cartitems")
public List<Item> getItemsInCart(@RequestParam("buyerId") Integer buyerId) { 
   // ...
}

Upvotes: 2

shakhawat
shakhawat

Reputation: 2727

Add @ResponseBody to your request handler method or annotate your controller as @RestController.

Make sure you have jackson converter on your classpath. You can follow this tutorial - https://www.journaldev.com/2552/spring-rest-example-tutorial-spring-restful-web-services

Upvotes: 0

Related Questions