ObjectMapper In the Jackson library

In the Jackson library, you can use ObjectMapper to deserialize a JSON string into a Java object. The ObjectMapper.readValue method is commonly used for this purpose. Here's how you can do it:

Example

JSON String:

{
  "name": "Alice",
  "age": 25
}

Java Class:

public class Person {
    private String name;
    private int age;

    // Getters and setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + '}';
    }
}

Code to Deserialize:

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonToObjectExample {
    public static void main(String[] args) throws Exception {
        String jsonString = "{ \"name\": \"Alice\", \"age\": 25 }";

        // Create ObjectMapper instance
        ObjectMapper mapper = new ObjectMapper();

        // Convert JSON string to Java object
        Person person = mapper.readValue(jsonString, Person.class);

        // Print the object
        System.out.println(person);
    }
}

Output:

Person{name='Alice', age=25}

Explanation

  1. Define the Java Class: Ensure the class has fields matching the JSON structure. Include getters, setters, and optionally toString for easy debugging.
  2. Use readValue: Call mapper.readValue(jsonString, Person.class) to map the JSON string to the Java object.
  3. ObjectMapper: This is the primary class in Jackson for converting between JSON and Java objects.

Additional Notes

  • Customizing Field Names: If JSON field names differ from Java field names, use the @JsonProperty annotation.
    public class Person {
        @JsonProperty("full_name")
        private String name;
        // Rest of the class...
    }
    
  • Handling Collections: Use a TypeReference when deserializing lists or maps.
    List<Person> people = mapper.readValue(jsonArrayString, new TypeReference<List<Person>>() {});
    

댓글

이 블로그의 인기 게시물

To switch to a specific tag in a Git repository

How to checkout branch of remote git, 깃 리모트 브랜치 체크아웃

Using the MinIO API via curl

To download a file from MinIO using Spring Boot, 스프링부트 Minio 사용하기

리눅스의 부팅과정 (프로세스, 서비스 관리)

Chromium 개발 환경 세팅, 크로미움 개발 준비하기

Joining an additional control plane node to an existing Kubernetes cluster

urllib3 with proxy settings

CDPEvents in puppeteer

Avro + Grpc in python