I need to parse an array of strings (identifiers) using Jackson. I didn't find any example of it on the inte.net, 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",
...
]
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);
}
}
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.