4

I need to parse an array of strings (identifiers) using Jackson. I didn't find any example of it on the internet, all of them show how to deserialize arrays of objects of some class, but I need just to parse an array of strings (without writing a model class for it), how can I do that? Example of JSON:

[
"UUID",
"UUID",
...
]
1

1 Answer 1

9

You can use the ObjectMapper.readValue() method with a TypeReference to get a list of strings:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

public class Test {
    public static void main(String[] args) throws IOException {
        String json = "[\"UUID\",\"UUID\"]";
        ObjectMapper mapper = new ObjectMapper();
        List<String> values = mapper.readValue(json,
                new TypeReference<List<String>>() {});
    }
}

Or you can use the ObjectMapper.readValue() method with the String[].class to get an array of strings:

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
        String json = "[\"UUID\",\"UUID\"]";
        ObjectMapper mapper = new ObjectMapper();
        String[] values = mapper.readValue(json, String[].class);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.