Java 在 Spring RESTful 服务中生成和使用自定义 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26115076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:52:03  来源:igfitidea点击:

Producing and consuming custom JSON Objects in Spring RESTful services

javajsonspringrestpost

提问by user592748

I have some JSON Objects that are more complex than the JSON representations of the java objects I have. I have methods that build these JSON Objects and I would like to return and consume these directly. I use org.jsonlibrary to build my JSONs. I could get the GETmethod working by returning the JSON Object as a String. Is this the correct way to go about it?

我有一些 JSON 对象,它们比我拥有的 Java 对象的 JSON 表示更复杂。我有构建这些 JSON 对象的方法,我想直接返回和使用这些对象。我使用org.json库来构建我的 JSON。我可以GET通过将 JSON 对象作为String. 这是正确的方法吗?

@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();
}

Now I want to know how do I consume a JSON Object? As a string and convert it to a JSON Object?

现在我想知道如何使用 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();
    }

Is this the correct way to go about my problem? I am a novice, so kindly point out anything that can be done better. Please note: I do not want to return POJOs.

这是解决我的问题的正确方法吗?我是新手,所以请指出任何可以做得更好的地方。请注意:我不想返回 POJO。

采纳答案by RE350

I think using Hymanson library you can do something like below.

我认为使用 Hymanson 库,您可以执行以下操作。

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

回答by kemenov

You can use Hymanson lib, Hymanson allows convert to/from json using spring mvc.

您可以使用 Hymanson lib,Hymanson 允许使用 spring mvc 与 json 进行转换。

  1. Spring configure @ResponseBody JSON format
  2. Hymanson 2.0 with Spring 3.1
  1. Spring配置@ResponseBody JSON格式
  2. Hyman逊 2.0 与 Spring 3.1

回答by paul

I much rather the alternative to use Hymanson with Spring mvc since you dont have to worry of the serialization and deserialization of your objects/json-json/object. But if you still want to the process I like to use gson of google.

我更愿意将 Hymanson 与 Spring mvc 一起使用,因为您不必担心对象/json-json/object 的序列化和反序列化。但是如果你还想要这个过程我喜欢用google的gson。

http://www.javacreed.com/simple-gson-example/

http://www.javacreed.com/simple-gson-example/

回答by Hypothetical inthe Clavicle

I couldn't get the auto serialization and deserialization to work using the default Spring boot beans. In the end, this worked well for me after including Project Lombok and apache BeanUtils. Spring calls a String arg constructor if it can't automatically do the serialization.

我无法使用默认的 Spring 引导 bean 使自动序列化和反序列化工作。最后,在包含 Project Lombok 和 apache BeanUtils 后,这对我来说效果很好。如果 Spring 不能自动执行序列化,则调用 String 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);
    }
}

http://commons.apache.org/proper/commons-beanutils/download_beanutils.cgihttps://projectlombok.org/

http://commons.apache.org/proper/commons-beanutils/download_beanutils.cgi https://projectlombok.org/