Convertir une chaîne JSON en mappage - Jackson

Jackson - Convertir la chaîne JSON en carte

Dans Jackson, nous pouvons utilisermapper.readValue(json, Map.class) pour convertir une chaîne JSON en unMap

P.S Tested with Jackson 2.9.8

pom.xml

    
        com.fasterxml.jackson.core
        jackson-databind
        2.9.8
    

1. Chaîne JSON à mapper

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>() {});

            System.out.println(map);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Sortie

{name=example, age=37}

2. Mapper à la chaîne 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();
        }


    }
}

Sortie

{"name":"example","age":"37"}
{
  "name" : "example",
  "age" : "37"
}

3. Tableau JSON à mapper?

3.1 JSON array string like this

[{"age":29,"name":"example"}, {"age":30,"name":"fong"}]

Il devrait être converti enList, au lieu deMap, par exemple:

    // convert JSON array to List
    List list = Arrays.asList(mapper.readValue(json, Person[].class));