[Java] JSON 파싱하기 (jackson/gson/json-simple)
Java

[Java] JSON 파싱하기 (jackson/gson/json-simple)

728x90

 

JSON 파싱시 자주 쓰이는 라이브러리 3개로 JSON을 파싱하는 예제를 소개합니다.

라이브러리

https://github.com/jhl8041/code-collection/tree/main/json-parsing <- github 예제

 

예제 JSON

// JSON Object
{
    "id": 1,
    "name": "Anna"
}
String jsonStr = "{\"id\" : 1, \"name\" : \"Anna\"}";

// JSON Array
[
    {
         "id": 1,
         "name": "Anna"
    },
    {
         "id": 2,
         "name": "Brian"
    }
]
String jsonArrStr = "[{\"id\" : 1, \"name\" : \"Anna\"}, {\"id\" : 2, \"name\" : \"Brian\"}]";

// Nested JSON (JSON 내부에 Object 또는 Array가 nest 되어있음)
{
    "id": 2,
    "group_name": "group1",
    "student_list": [
        {
            "name": "Danny",
            "classroom": "1-2",
            "hobby": ["golf", "tennis", "squash"]
        },
        {
            "name": "Tony",
            "classroom": "2-5",
            "hobby": ["football", "baseball", "basketball"]
        }
    ]
}
String jsonNestedStr = "{\"id\":2,\"name\":\"group1\",\"student_list\":[{\"name\":\"Danny\",\"classroom\":\"1-2\",\"hobby\":[\"golf\",\"tennis\",\"squash\"]},{\"name\":\"Tony\",\"classroom\":\"2-5\",\"hobby\":[\"football\",\"baseball\",\"basketball\"]}]}";

GSON

parsing 로직

import com.dannyjae.jsonparsing.gson.object.Group;
import com.dannyjae.jsonparsing.gson.object.Sample;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class GsonSample {

  // JSON String 에서 객체로 맵핑
  public void jsonToObject(String jsonStr) {
    Gson gson = new Gson();
    Sample sample = gson.fromJson(jsonStr, Sample.class);

    System.out.println(sample);
  }
  
  // JSON String 에서 Map 으로 맵핑
  public void jsonToMap(String jsonStr) {
    Gson gson = new Gson();
    Map<String, Object> gsonMap = gson.fromJson(jsonStr, new TypeToken<Map<String, Object>>(){}.getType());

    System.out.println(gsonMap);
  }

  // JSON String (Array) 에서 Array로 맵핑
  public void jsonArrayToObjectArray(String jsonArrStr) {
    Gson gson = new Gson();
    Sample[] sampleArr = gson.fromJson(jsonStr, Sample[].class);

    System.out.println(Arrays.toString(sampleArr));
  }

  // JSON String (Array) 에서 List 로 맵핑
  public void jsonArrayToObjectList(String jsonArrStr) {
    Gson gson = new Gson();
    List<Sample> sampleList = gson.fromJson(jsonStr, new TypeToken<List<Sample>>(){}.getType());

    System.out.println(sampleList);
  }

  // JSON String (nested) 에서 객체로 맵핑
  public void jsonNestedToObject(String jsonNestedStr) {
    Gson gson = new Gson();
    Group group = gson.fromJson(jsonStr, Group.class);

    System.out.println(group);
  }
}

 

객체 구성

@ToString
@Setter
public class Sample {
  @SerializedName("id")
  private Long id;

  @SerializedName("name")
  private String name;
}
------------------------------------------------
@ToString
@Setter
public class Group {
  @SerializedName("id")
  private Long id;

  @SerializedName("name")
  private String name;

  @SerializedName("student_list")
  private List<Student> studentList;
}
------------------------------------------------
@ToString
@Setter
public class Student {
  @SerializedName("name")
  private String name;

  @SerializedName("classroom")
  private String classroom;

  @SerializedName("hobby")
  private List<String> hobby;
}

 


JACKSON

parsing 로직

import com.dannyjae.jsonparsing.jackson.object.Group;
import com.dannyjae.jsonparsing.jackson.object.Sample;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class JacksonSample {

  // JSON String 에서 객체로 맵핑
  public void jsonToObject(String jsonStr) throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    Sample sample = objectMapper.readValue(jsonStr, Sample.class);

    System.out.println(sample);
  }

  // JSON String 에서 Map 으로 맵핑
  public void jsonToMap(String jsonStr) throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    Map<String, Object> jacksonMap = objectMapper.readValue(jsonStr, new TypeReference<Map<String, Object>>(){});

    System.out.println(jacksonMap);
  }

  // JSON String (Array) 에서 Array로 맵핑
  public void jsonArrayToObjectArray(String jsonArrStr) throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    Sample[] sampleArr = objectMapper.readValue(jsonStr, Sample[].class);

    System.out.println(Arrays.toString(sampleArr));
  }

  // JSON String (Array) 에서 List 로 맵핑
  public void jsonArrayToObjectList(String jsonArrStr) throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    List<Sample> sampleList = objectMapper.readValue(jsonStr, new TypeReference<List<Sample>>(){});

    System.out.println(sampleList);
  }

  // JSON String (nested) 에서 객체로 맵핑
  public void jsonNestedToObject(String jsonNestedStr) throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    Group group = objectMapper.readValue(jsonStr, Group.class);

    System.out.println(group);
  }
}

객체 구성

@ToString
@Setter
public class Group {
  @JsonProperty("id")
  private Long id;

  @JsonProperty("name")
  private String name;

  @JsonProperty("student_list")
  private List<Student> studentList;
}
------------------------------------------------
@ToString
@Setter
public class Sample {
  @JsonProperty("id")
  private Long id;

  @JsonProperty("name")
  private String name;
}
------------------------------------------------
@ToString
@Setter
public class Student {
  @JsonProperty("name")
  private String name;

  @JsonProperty("classroom")
  private String classroom;

  @JsonProperty("hobby")
  private List<String> hobby;
}

JSON-SIMPLE

parsing 로직

import com.dannyjae.jsonparsing.jsonsimple.object.Group;
import com.dannyjae.jsonparsing.jsonsimple.object.Sample;
import com.dannyjae.jsonparsing.jsonsimple.object.Student;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.util.*;

public class JsonSimpleSample {

  // JSON String 에서 객체로 맵핑
  public void jsonToObject(String jsonStr) throws ParseException {
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonStr);
    Sample sample = Sample.builder()
            .id((Long) jsonObject.get("id"))
            .name((String) jsonObject.get("name"))
            .build();

    System.out.println(sample);
  }

  // JSON String 에서 Map 으로 맵핑
  public void jsonToMap(String jsonStr) throws ParseException {
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonStr);
    Map<String, Object> jsonSimpleMap = new HashMap<>();
    jsonSimpleMap.put("name", jsonObject.get("name"));
    jsonSimpleMap.put("id", jsonObject.get("id"));

    System.out.println(jsonSimpleMap);
  }

  // JSON String (Array) 에서 Array로 맵핑
  public void jsonArrayToObjectArray(String jsonArrStr) throws ParseException {
    JSONParser jsonParser = new JSONParser();
    JSONArray jsonArray = (JSONArray) jsonParser.parse(jsonStr);
    Sample[] sampleArr = new Sample[jsonArray.size()];
    for (int i=0;i<jsonArray.size();i++){
      JSONObject jsonObject = (JSONObject) jsonArray.get(i);
      sampleArr[i] = Sample.builder()
              .id((Long) jsonObject.get("id"))
              .name((String) jsonObject.get("name"))
              .build();
    }

    System.out.println(Arrays.toString(sampleArr));
  }

  // JSON String (Array) 에서 List 로 맵핑
  public void jsonArrayToObjectList(String jsonArrStr) throws ParseException {
    JSONParser jsonParser = new JSONParser();
    JSONArray jsonArray = (JSONArray) jsonParser.parse(jsonStr);
    List<Sample> sampleList = new ArrayList<>();
    for (Object o : jsonArray) {
      JSONObject jsonObject = (JSONObject) o;
      sampleList.add(Sample.builder()
              .id((Long) jsonObject.get("id"))
              .name((String) jsonObject.get("name"))
              .build());
    }

    System.out.println(sampleList);
  }

  // JSON String (nested) 에서 객체로 맵핑
  public void jsonNestedToObject(String jsonNestedStr) throws ParseException {
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonStr);

    JSONArray jsonArray = (JSONArray) jsonParser.parse(jsonObject.get("student_list").toString());
    List<Student> studentList = new ArrayList<>();
    for (Object object : jsonArray) {
      JSONObject jsonObjectStudent = (JSONObject) object;

      JSONArray jsonArrayHobby = (JSONArray) jsonParser.parse(jsonObjectStudent.get("hobby").toString());
      List<String> hobbyList = new ArrayList<>();
      for (Object hobbyObject : jsonArrayHobby) {
        hobbyList.add(hobbyObject.toString());
      }

      studentList.add(Student.builder()
              .name((String) jsonObjectStudent.get("name"))
              .classroom((String) jsonObjectStudent.get("classroom"))
              .hobby(hobbyList)
              .build());
    }
    Group group = Group.builder()
            .id((Long) jsonObject.get("id"))
            .name((String) jsonObject.get("name"))
            .studentList(studentList)
            .build();

    System.out.println(group);
  }
}

객체 구성

@ToString
@Builder
public class Group {
  private Long id;
  private String name;
  private List<Student> studentList;
}
------------------------------------------------
@ToString
@Builder
public class Sample {
  private Long id;
  private String name;
}
------------------------------------------------
@ToString
@Builder
public class Student {
  private String name;
  private String classroom;
  private List<String> hobby;
}

개인적으로는 gson, jackson 라이브러리가 여러 형태의 json을 파싱하여 사용하기 수월했던 것 같습니다! :)

728x90