Send JSON with arbitrary key values ​​using the REST service (Jersey / Jackson)

I want to send something like this from a client to a leisure service

  jsonObj = 
 {
    "info": {
        "field1": "val1" ..
 .....
        "fieldN": "valN" ..
    }
 }

And I’m not sure how I can deal with this with the help of the recreation service using

  Jersey and Jackson in Java 

I do not want to create a new information class using Jackson properties with field N, as they will always change. I just want to grab the jsonObject that is inside jsonObject and work with it like JsonObject.

Any thoughts?

+4
source share
2 answers

Assuming you have a root object that you are reading the result into, you can define docInfo as Map<String, Object> in your jsonObj. This will probably work, but I can't let go of him.

If you don't have a root object, you can simply use Map<String, Object> as your root object and play with it from there. This map may contain other maps for nested json objects.

+6
source

Yes, use a wrapper object with an embedded map, as @digitialjoel suggested. This is a concrete example:

 class DocInfo { private Map<String, Object> docInfo; public DocInfo() { super(); } public DocInfo(final Map<String, Object> docInfo) { super(); this.docInfo = docInfo; } // Getters, setters } final Map<String, Object> data = new LinkedHashMap<String, Object>(4); data.put("field1", "value1"); data.put("field2", "value2"); data.put("field3", "value3"); data.put("field4", "value4"); final DocInfo info = new DocInfo(data); final ObjectMapper mapper = new ObjectMapper(); final String json = mapper.writeValueAsString(info); System.out.println(json); 

Output:

{"DOCINFO": {"field1": "value1", "field2": "value2", "field3": "value3", "Field4": "value4"}}

+3
source

All Articles