ジャクソン– JSON文字列をマップに変換
ジャクソンでは、mapper.readValue(json, Map.class)を使用してJSON文字列をMapに変換できます
P.S Tested with Jackson 2.9.8
pom.xml
com.fasterxml.jackson.core jackson-databind 2.9.8
1. マップするJSON文字列
JacksonMapExample1.java
package com.example;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;
public class JacksonMapExample1 {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"example\", \"age\":\"37\"}";
try {
// convert JSON string to Map
Map map = mapper.readValue(json, Map.class);
// it works
//Map map = mapper.readValue(json, new TypeReference
出力
{name=example, age=37}
2. JSON文字列にマップする
JacksonMapExample2.java
package com.example;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
public class JacksonMapExample2 {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
Map map = new HashMap<>();
map.put("name", "example");
map.put("age", "37");
try {
// convert map to JSON string
String json = mapper.writeValueAsString(map);
System.out.println(json); // compact-print
json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);
System.out.println(json); // pretty-print
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
出力
{"name":"example","age":"37"}
{
"name" : "example",
"age" : "37"
}
3. マップするJSON配列?
3.1 JSON array string like this
[{"age":29,"name":"example"}, {"age":30,"name":"fong"}]
たとえば、MapではなくListに変換する必要があります。
// convert JSON array to List
List list = Arrays.asList(mapper.readValue(json, Person[].class));