简体   繁体   中英

Convert JsonObject from google to JsonNode to Jackson and then pass multiple JsonNode as an array to a web service

I have an application which has a list of JsonObject and which uses google GSON library. I need to send this list to my another service, which is using the Jackson library for JSON serialization and deserialization, this service extracts the each JsonObject and does some processing.

I have an experience of handling the JSON, coming to my web-service using the JsonNode of jackson in my Jersey resource. But in this case it would be an array of JsonNode.

[
    {
        "id" : 1,
        "firstName": "hello",
        "lastName": "world"
    },
    {
        "id" : 2,
        "firstName": "first",
        "lastName": "last"
    }
]

So my question is using which datatype of Jackson , I should be able to handle the array of JsonNode ?

found the solution, we can use the same JsonNode to handle the array of JSON, And then can use the size method of JsonNode to determine how many elements are there in JsonArray which is of type JsonNode .

Code sample:

public void test(JsonNode jsonNode) throws IOException {
        int size = jsonNode.size();
        HashMap<String, String> map = new HashMap<>();
        while (size > 0) {
            JsonNode message = jsonNode.get(--size);
            map.put(message.get("id").toString(), message.toString());
        }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM