Jackson - Konvertiert JSON-String in Map
In Jackson können wirmapper.readValue(json, Map.class) verwenden, um eine JSON-Zeichenfolge inMap zu konvertieren
P.S Tested with Jackson 2.9.8
pom.xml
com.fasterxml.jackson.core jackson-databind 2.9.8
1. JSON-Zeichenfolge zu Map
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
Ausgabe
{name=example, age=37}
2. Zuordnung zur JSON-Zeichenfolge
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();
}
}
}
Ausgabe
{"name":"example","age":"37"}
{
"name" : "example",
"age" : "37"
}
3. JSON-Array zuordnen?
3.1 JSON array string like this
[{"age":29,"name":"example"}, {"age":30,"name":"fong"}]
Es sollte inList anstatt inMap konvertiert werden, zum Beispiel:
// convert JSON array to List
List list = Arrays.asList(mapper.readValue(json, Person[].class));
Note
Lesen Sie dieseJackson
– Convert JSON array string to List