티스토리 뷰

JSON 데이터가 다른 객체나 배열을 가지고 있지 않은 단순한 데이터라면 Android에서 클래스로 정의하는 것은 간단하다.

데이터 속성을 바로 클래스 속성으로 매핑시키면 되니까!


그런데 배열이나 객체를 품고 있다면?

예를 들어 다음과 같은 JSON 데이터는 어떻게 클래스로 변환해야 할까?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
    "_id""582...ba2",
    "title""텀블러",
    "price"35000,
    "url""http://blog.imcreator.com",
    "provider""582...b95",
    "__v"0,
    "ship": {
      "text""2500원 (5만원 이상 무료배송)",
      "price"2500
    },
    "option": [
      "흰색",
      "분홍색"
    ]
}
cs


"ship" 속성은 객체이고, option은 배열이다.


물론 이걸 직접 매핑을 시킬 수도 있겠지만 JSON 데이터를 JAVA 클래스로 변환해주는 사이트가 있다.

POJO란 'Plain Old Java Object'의 약자이다.

 extends, implements, 또는 annotation을 사용하지 않은 순수한 객체

http://www.jsonschema2pojo.org/



Retrofit에서 GSON을 사용하면 Gson Annotation style를 추가할 수 있고,


아래 옵션 선택에 따라서 빌더 메서드, 게터/세터, 생성자 등 자동으로 생성시켜준다.

결과는 아래 Preview 버튼을 눌러서 확인할 수 있고, 위의 옵션에서 Preview를 눌렀을 때 아래와 같이 

Example 클래스와 Ship 클래스를 확인 및 복사할 수 있다.

(코드가 너무 길어져 생성된 게터/세터 메서드는 삭제했다)


-----------------------------------com.example.Example.java-----------------------------------

package com.example;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class Example {

@SerializedName("_id")
@Expose
private String id;
@SerializedName("title")
@Expose
private String title;
@SerializedName("price")
@Expose
private Integer price;
@SerializedName("url")
@Expose
private String url;
@SerializedName("provider")
@Expose
private String provider;
@SerializedName("__v")
@Expose
private Integer v;
@SerializedName("ship")
@Expose
private Ship ship;
@SerializedName("option")
@Expose
private List<String> option = new ArrayList<String>();

-----------------------------------com.example.Ship.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class Ship {

@SerializedName("text")
@Expose
private String text;
@SerializedName("price")
@Expose
private Integer price;


참고문헌

jsonschema2pojo, http://www.jsonschema2pojo.org/

Using Retrofit to access JSON arrays, http://stackoverflow.com/questions/21815008/using-retrofit-to-access-json-arrays

댓글