Java 在Spring RESTful服务中生成和使用自定义JSON对象
我有一些JSON对象,它们比我拥有的java对象的JSON表示更复杂。我有构建这些JSON对象的方法,我想直接返回并使用这些方法。我使用Java 在Spring RESTful服务中生成和使用自定义JSON对象,java,json,spring,rest,post,Java,Json,Spring,Rest,Post,我有一些JSON对象,它们比我拥有的java对象的JSON表示更复杂。我有构建这些JSON对象的方法,我想直接返回并使用这些方法。我使用org.json库来构建我的json。通过将JSON对象作为字符串返回,我可以使get方法工作。这是正确的方法吗 @RequestMapping(value = "/getjson", method = RequestMethod.GET, produces="application/json") @ResponseBody public String getJ
org.json
库来构建我的json。通过将JSON对象作为字符串返回,我可以使get
方法工作。这是正确的方法吗
@RequestMapping(value = "/getjson", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public String getJson() {
JSONObject json = new JSONObject();
JSONObject subJson = new JSONObject();
subJson .put("key", "value");
json.put("key", subJson);
return json.toString();
}
现在我想知道如何使用JSON对象?作为字符串并将其转换为JSON对象
@RequestMapping(value = "/post", method = RequestMethod.POST, produces="application/json", consumes="application/json")
@ResponseBody
public String post(@RequestBody String json) {
JSONObject obj = new JSONObject(json);
//do some things with json, put some header information in json
return obj.toString();
}
这是解决我问题的正确方法吗?我是新手,所以请指出任何可以做得更好的地方。请注意:我不想返回POJO。您可以使用jackson库,jackson允许使用spring mvc转换json
我更倾向于将Jackson与springmvc结合使用,因为您不必担心对象/json/object的序列化和反序列化。但是如果你还想继续这个过程,我喜欢用谷歌的gson
我认为使用jackson library,您可以执行以下操作
@RequestMapping(value = "/getjson", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public String getJson() {
//your logic
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(json);
}
@RequestMapping(value = "/post", method = RequestMethod.POST, produces="application/json", consumes="application/json")
@ResponseBody
public String post(@RequestBody String json) {
POJO pj = new POJO();
ObjectMapper mapper = new ObjectMapper();
pj = mapper.readValue(json, POJO.class);
//do some things with json, put some header information in json
return mapper.writeValueAsString(pj);
}
我无法使用默认的SpringBootBean实现自动序列化和反序列化。最后,在加入了Lombok项目和apache BeanUtils之后,这对我来说非常有效。如果Spring不能自动执行序列化,它将调用字符串arg构造函数
@PostMapping("/create")
@ResponseBody
public User createUser(HttpServletRequest request, @RequestParam("user") User u) throws IOException {
LOG.info("Got user! " + u);
return u;
}
@ToString() @Getter() @Setter() @NoArgsConstructor()
public class User {
private String email;
private String bio;
private String image;
private String displayName;
private String userId;
private long lat;
private long lng;
public User(String json) throws JsonParseException, JsonMappingException, IOException, IllegalAccessException, InvocationTargetException {
ObjectMapper om = new ObjectMapper();
User u = om.readValue(json, User.class);
BeanUtils.copyProperties(this, u);
}
}