gson moshi 예제

Gson과 Moshi는 모두 Java 및 Kotlin에서 JSON 데이터를 처리하는 라이브러리입니다. 이번 포스트에서는 Gson과 Moshi의 예제를 통해 두 라이브러리의 기능과 성능을 비교해보겠습니다.

Gson

Gson은 Google에서 개발한 JSON 라이브러리로, Java 객체를 JSON 문자열로 변환하거나, JSON 문자열을 Java 객체로 변환하는 기능을 제공합니다.

다음은 Gson을 사용하여 JSON 문자열을 Java 객체로 변환하는 예제입니다:

import com.google.gson.Gson;

public class GsonExample {
    public static void main(String[] args) {
        String json = "{\"name\":\"John\", \"age\":30}";

        Gson gson = new Gson();
        Person person = gson.fromJson(json, Person.class);

        System.out.println(person.getName());
        System.out.println(person.getAge());
    }
}

class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

위의 예제에서는 Gson 객체를 생성한 후 fromJson() 메서드를 사용하여 JSON 문자열을 Java 객체로 변환합니다. 변환된 객체의 필드에 접근하여 값을 출력합니다.

Moshi

Moshi는 Square에서 개발한 JSON 라이브러리로, Gson보다 더 간단한 API와 높은 성능으로 유명합니다.

다음은 Moshi를 사용하여 JSON 문자열을 Java 객체로 변환하는 예제입니다:

import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MoshiExample {
    public static void main(String[] args) throws IOException {
        String json = "{\"name\":\"John\", \"age\":30}";

        Moshi moshi = new Moshi.Builder().build();
        JsonAdapter<Person> jsonAdapter = moshi.adapter(Person.class);
        Person person = jsonAdapter.fromJson(json);

        System.out.println(person.getName());
        System.out.println(person.getAge());
    }
}

class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

위의 예제에서는 Moshi 객체를 생성한 후 adapter() 메서드를 사용하여 JSON 문자열을 Java 객체로 변환합니다. 변환된 객체의 필드에 접근하여 값을 출력합니다.

Gson vs Moshi

Gson과 Moshi 모두 유용하고 성능이 우수한 JSON 처리 라이브러리입니다. Gson은 더 많은 커스터마이징 옵션과 함께 Java와 Kotlin 모두에서 널리 사용됩니다. 반면 Moshi는 Gson보다 간단한 API와 더 높은 성능을 제공합니다. 따라서 프로젝트의 요구사항과 성능에 따라 선택하면 됩니다.

#Gson #Moshi