简体   繁体   中英

Spring return string as json without creating a pojo to serialize

I am proxying a web request using spring. The response from the end server is a json, i want to pass the json as is to client without creating a pojo for serializing/deserializing. Is this possible?

@RequestMapping(value = "/sample")
@ResponseBody
Object proxyTesting(){
    String result;
    //after proxy result={"success":true , "data":5}
    return result;
}

at the client end i expect it to be as is. ie {"success":true , "data":5}

In reality, the result string is nested, and i don't want to create interim pojo's for them.

Yes, this is possible.

The question "Spring MVC - How to return simple String as JSON in Rest Controller " is similar to yours: https://stackoverflow.com/a/33352362/12485815

Here is one answer provided:

  @RequestMapping(value="/user/addUser", method=RequestMethod.POST)
  @ResponseBody
  public String addUser(@ModelAttribute("user") User user) {
     
    if (user != null) {
      logger.info("Inside addIssuer, adding: " + user.toString());
    } else {
      logger.info("Inside addIssuer...");
    }
    users.put(user.getUsername(), user);
    return "{\"success\":1}";
  }

Bad practice but you want something like this

@RequestMapping(value = "/sample", produces = "application/json") 
@ResponseBody 
String proxyTesting(){
String result;
return "{ \"success\":\"true\", \"data\":\""+result+"\"}"; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM