mapping nested json and POJOs using Spring

守給你的承諾、 提交于 2020-01-14 12:51:53

问题


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:

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:

{
 "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?

@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

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.

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

Thanks


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/22212158/mapping-nested-json-and-pojos-using-spring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!