如何在JAVA中返回正确的JSON

时间:2019-01-16 14:55:43

标签: java json spring

 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;
}

大家好!我上面的代码以这种格式返回JSON:

["{\"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}"]

但是我希望它不加反斜杠。您是否知道如何将其转换为适当的JSON数组?

谢谢!

2 个答案:

答案 0 :(得分:2)

请勿使用JSONObject映射到JSON,也不要直接读取String。为响应创建新的POJO类,并让RestTemplate完成工作。在内部,Spring将使用合适的转换器来映射对象:

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

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

您的控制器方法还应该返回Item而不是String

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

答案 1 :(得分:0)

@ResponseBody添加到您的请求处理程序方法中,或将控制器注释为@RestController

确保您的类路径上有jackson转换器。您可以按照本教程进行操作-https://www.journaldev.com/2552/spring-rest-example-tutorial-spring-restful-web-services