Java 使用 Spring 映射嵌套的 json 和 POJO

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22212158/
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-13 14:21:12  来源:igfitidea点击:

mapping nested json and POJOs using Spring

javajsonspringpojo

提问by mohi

I am implementing a REST API which send and receive data with json(I am totally new to this API design). I am using Spring framework and requestbody/responsebody for mapping. Initially, I had a pojo like this:

我正在实现一个 REST API,它使用 json 发送和接收数据(我对这个 API 设计完全陌生)。我正在使用 Spring 框架和 requestbody/responsebody 进行映射。最初,我有一个这样的 pojo:

public class Action implements Serializable {

    @Id
    private String id;
    private String name;
    private String applicationId;
    private String timeStamp;
    private String username;
    private String options;
    //Getters and Setters
}

and the json format for this pojo is like this:

这个 pojo 的 json 格式是这样的:

{
 "id": "11954cd5-eec3-4f68-b0e8-a4d9b6a976a9",
 "name": "kill button",
 "applicationId": "34fa7bbf-e49f-4f2a-933a-de26b9fdb0f1",
 "timeStamp": "2014-03-05T11:51+0000",
 "username": "user1783",
 "options": "facebook app" 
}

This is how the controller look like:I do not get any json, Spring is converting already to java object, should it do it manually myself?

这是控制器的样子:我没有得到任何 json,Spring 已经转换为 java 对象,它应该自己手动执行吗?

@RequestMapping(value = "applications/{appId}/actions", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
@ResponseBody
public Action addAction(@PathVariable String appId, @RequestBody Action action) {
    return actionService.add(appId, action);
}

you can find a pretty json format of it here: https://gist.github.com/bakharzy/8948950

你可以在这里找到一个漂亮的 json 格式:https: //gist.github.com/bakharzy/8948950

I want to change the last pair in the json to be a json itself as it is shown in the second json format in gist. So user can send more information. Now that I have a new format for json which is kind of json in json, how should I change the pojo (private String options;) to store the data coming from second json format. Note that the inner json can have arbitrary number of pairs.

我想将 json 中的最后一对更改为 json 本身,因为它以 gist 中的第二种 json 格式显示。因此用户可以发送更多信息。现在我有了一种新的 json 格式,它是 json 中的一种 json,我应该如何更改 pojo(私有字符串选项;)来存储来自第二种 json 格式的数据。请注意,内部 json 可以有任意数量的对。

My first idea is to change the options in pojo to something like Hash object. Is it doable? If so, how?

我的第一个想法是将 pojo 中的选项更改为 Hash 对象之类的东西。可行吗?如果是这样,如何?

Thanks

谢谢

采纳答案by ninnemannk

Just use a nested Object like so:

只需像这样使用嵌套对象:

public class Action implements Serializable {

    @Id
    private String id;
    private String name;
    private String applicationId;
    private String timeStamp;
    private String username;
    private Map<String, String> options;
    //Getters and Setters
}

This will give you this format:

这将为您提供以下格式:

{
    "id": "11954cd5-eec3-4f68-b0e8-a4d9b6a976a9",
    "name": "kill button",
    "applicationId": "34fa7bbf-e49f-4f2a-933a-de26b9fdb0f1",
    "timeStamp": "2014-03-05T11:51+0000",
    "username": "user1783",
    "options":{
          "data": "Click Here",
          "size": "36",
          "application":"facebook app"
     }
}

UPDATE:- Adding test to prove that the solution does indeed work.

更新:- 添加测试以证明该解决方案确实有效。

public class ActionTest {

        @Test
        public void testObjectToJson() throws JsonProcessingException {

            Action action = new Action();
            action.setId("id");
            action.setUsername("username");
            action.setApplicationId("applicationId");
            action.setName("name");
            action.setTimeStamp("timestamp");
            Map<String, String> map = Maps.newHashMap();
            map.put("key", "value");
            map.put("key2", "value2");
            action.setOptions(map);

            ObjectMapper mapper = new ObjectMapper();

            String value = mapper.writeValueAsString(action);
            System.out.println(value);
        }

        @Test
        public void testJsonToObject() throws IOException {

            String json = "{\"id\":\"id\",\"name\":\"name\",\"applicationId\":\"applicationId\",\"timeStamp\":\"timestamp\",\"username\":\"username\",\"options\":{\"key\":\"value\", \"key2\":\"value2\"}}";

            ObjectMapper mapper = new ObjectMapper();

            Action value = mapper.readValue(json, Action.class);
            System.out.println(value);
        }
    }

    class Action {

        private String id;
        private String name;
        private String applicationId;
        private String timeStamp;
        private String username;
        private Map<String, String> options;

        public Action() {}

        @Override
        public String toString() {
            final StringBuffer sb = new StringBuffer("Action{");
            sb.append("id='").append(id).append('\'');
            sb.append(", name='").append(name).append('\'');
            sb.append(", applicationId='").append(applicationId).append('\'');
            sb.append(", timeStamp='").append(timeStamp).append('\'');
            sb.append(", username='").append(username).append('\'');
            sb.append(", options=").append(options);
            sb.append('}');
            return sb.toString();
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getApplicationId() {
            return applicationId;
        }

        public void setApplicationId(String applicationId) {
            this.applicationId = applicationId;
        }

        public String getTimeStamp() {
            return timeStamp;
        }

        public void setTimeStamp(String timeStamp) {
            this.timeStamp = timeStamp;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public Map<String, String> getOptions() {
            return options;
        }

        public void setOptions(Map<String, String> options) {
            this.options = options;
        }
    }

回答by Hot Licks

Map<String, Object> innerMap = new WhateverMap<String, Object>();
innerMap.put("data", "click here");
innerMap.put("size", "36");
innerMap.put("application", "facebook app");

Map<String, Object> outerMap = new WhateverMap<String, Object>();
outerMap.put("name", "kill button");
outerMap.put("username", "user1783");
outerMap.put("options", innerMap);

String jsonString = jsonEncoder.encode(outerMap);