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",
...
]
CodePudding user response:
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);
}
}