2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JSONをJavaオブジェクトに変換

Posted at

入力パラメーターをJSONで受け取ってJavaオブジェクトに変換する処理がよくあるので備忘録

入力パラメーター

{"id":100,"name":"らつき","age":25}

変換先のPersonクラス

public class Person {
    private int id;
    private String name;
    private int age;
    
    public Person() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    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;
    }
}

ObjectMapper

JacksonというJSONライブラリで提供される、JavaオブジェクトとJSONの相互変換を行うためのクラス。
ObjectMapperを使用することで、JavaオブジェクトをJSON文字列に変換したり、JSON文字列をJavaオブジェクトに変換したりすることができる。ObjectMapperは、複雑なJSONデータを扱う場合にも便利。
例えば、ネストされたJSONオブジェクトを含むJSON文字列を、Javaオブジェクトの階層構造にマッピングすることができる。

ObjectMapperを使用して変換する

public class SyainService {
	public static void main(String[] args) {
        String json = "{\"id\":100,\"name\":\"らつき\",\"age\":25}";
        ObjectMapper mapper = new ObjectMapper();

        try {
            //mapper.readValue(json,変換したいクラス);
            Person person = mapper.readValue(json,Person.class);
            System.out.println(person.getId());
            System.out.println(person.getName());
            System.out.println(person.getAge());
        } catch(JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

実行結果
JSONのキーとJavaのフィールド名が一致して入れば変換を行えることが分かる

100
らつき
25
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?