How to get plain JSON data in jersey REST implemen

2019-07-27 10:05发布

问题:

If we have a POJO class, then we can map it with some incoming JSON. I am struggling to find out a way by which I can just have all plain json value inside.

For ex.

{
    "macro_tasks": [
        {
            "id": "cc5cee68-c1e5-4396-987b-c68559399186",
            "label": "consi-1",
            "name": "Consi 1",
            "project_id": "82d1e463-1bb1-42d3-9adc-9e0d5848d139",
            "creator_id": null,
            "created_at": null,
            "updated_at": null,
            "meta_data": {
                "key1": "value1",
                "key2": 321
          }
        }
    ]
}

Here meta_data is of JSON type which can keep changing its values inside. So I cannot map it with some POJO class.

public class MacroTask {

    private UUID id;
    private String label;
    private String name;

    private UUID projectId;

    private UUID creatorId;

    private String createdAt;

    private String updatedAt;

    private <some data type> meta_data;

//getter and setter

Is there any way to get plain JSON data and use it in code and dump into DB [we are using PostgreSQL, which supports jsonb type.]

回答1:

I solved it by using Generic JSON type, Jackson's JsonNode. It has some drawbacks as I heard, but I am giving it a try. So far, it's working as per expectations. I will update if I face any challenge or I find any better solution.



回答2:

You can use map; like

private Map<String, Object> meta_data;


回答3:

I got following error

Can not deserialize instance of java.lang.String out of START_OBJECT

I was using this code for json string to HasMap conversion.

Map map = mapper.readValue(jsonString, new TypeReference<HashMap<String,String>>(){});

I replaced it with.

Map map = mapper.readValue(jsonString, new TypeReference<HashMap<String,Object>>(){});


回答4:

Why not use meta_data as a field of type string instead of array? Then you could add the plain JSON as a string and use this value in your backend.

//add json as string value to this field    
private String meta_data;