Google Library 중에 하나인 Gson
Java <=> JSON 으로 사용되는 라이브러리이며 많이들 쓰이는듯 하다.
사이트: https://code.google.com/p/google-gson/
API: http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html
User Guide: https://sites.google.com/site/gson/gson-user-guide/
이것저것 알아봤는데 아까울정도로 열심히 알아봐서 이렇게 정리를..;;
Company.java
import java.util.ArrayList;
import java.util.List;
/**
* Created by 1004lucifer on 2015-04-08.
*/
public class Company {
private String name;
private List<Person> employees;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public List<Person> getEmployees() { return employees; }
public void setEmployees(List<Person> employees) { this.employees = employees; }
public static class Person {
private String name;
private String age;
private String sex;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getAge() { return age; }
public void setAge(String age) { this.age = age; }
public String getSex() { return sex; }
public void setSex(String sex) { this.sex = sex; }
public String toString() { return "name: " + name + "\tage: " + age + "\tsex: " + sex; }
}
public static Company getCompanyDummy() {
Company company = new Company();
company.setName("1004lucifer's Company");
List<Company.Person> personList = new ArrayList<Person>();
Company.Person person = new Person();
person.setName("1004lucifer");
person.setAge("30");
person.setSex("M");
personList.add(person);
person = new Person();
person.setName("vvoei");
person.setAge("29");
person.setSex("M");
personList.add(person);
person = new Person();
person.setName("John");
person.setSex("M");
personList.add(person);
person = new Person();
person.setName("Jane");
person.setAge("20");
personList.add(person);
person = new Person();
personList.add(person);
company.setEmployees(personList);
return company;
}
}
단순 JavaObject(Class) <=> JSON 변환 방법
1004lucifer
TestGsonUser.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.List;
/**
* Created by 1004lucifer on 2015-04-08.
*/
public class TestGsonUser {
public static void main(String[] argv) {
Company company = Company.getCompanyDummy();
System.out.println("========= Object => Json ==========");
String company2Json = new Gson().toJson(company);
System.out.println(company2Json);
System.out.println("========= Json => Object =========");
Company json2Company = new Gson().fromJson(company2Json, Company.class);
printCompanyObject(json2Company);
System.out.println("========= Object => Json =========");
String company2JsonIsNull = new GsonBuilder().serializeNulls().create().toJson(company);
System.out.println(company2JsonIsNull);
System.out.println("========= Json => Object =========");
Company json2CompanyIsNull = new Gson().fromJson(company2Json, Company.class);
printCompanyObject(json2CompanyIsNull);
}
private static void printCompanyObject(Company company) {
List<Company.Person> personList = company.getEmployees();
System.out.println("userName: " + company.getName());
for (Company.Person person : personList) {
System.out.println(person);
}
}
}
결과
{"name":"1004lucifer\u0027s Company","employees":[{"name":"1004lucifer","age":"30","sex":"M"},{"name":"vvoei","age":"29","sex":"M"},{"name":"John","sex":"M"},{"name":"Jane","age":"20"},{}]}
========= Json => Object =========
userName: 1004lucifer's Company
name: 1004lucifer age: 30 sex: M
name: vvoei age: 29 sex: M
name: John age: null sex: M
name: Jane age: 20 sex: null
name: null age: null sex: null
========= Object => Json =========
{"name":"1004lucifer\u0027s Company","employees":[{"name":"1004lucifer","age":"30","sex":"M"},{"name":"vvoei","age":"29","sex":"M"},{"name":"John","age":null,"sex":"M"},{"name":"Jane","age":"20","sex":null},{"name":null,"age":null,"sex":null}]}
========= Json => Object =========
userName: 1004lucifer's Company
name: 1004lucifer age: 30 sex: M
name: vvoei age: 29 sex: M
name: John age: null sex: M
name: Jane age: 20 sex: null
name: null age: null sex: null
String JSON 편집 방법
1004lucifer
Java Class 가 없는경우 JSON 값은 다음과 같이 작업을 했다.
TestGsonSetJsonValue.java
import com.google.gson.*;
import com.skt.tservice.network.module.EncryptSDK;
import java.util.Iterator;
import java.util.Map;
/**
* Created by 1004lucifer on 2015-04-08.
*/
public class TestGsonSetJsonValue {
public static void main(String[] argv) {
String companyJson= "{\"name\":\"1004lucifer\\u0027s Company\",\"employees\":[{\"name\":\"1004lucifer\",\"age\":\"30\",\"sex\":\"M\"},{\"name\":\"vvoei\",\"age\":\"29\",\"sex\":\"M\"},{\"name\":\"John\",\"sex\":\"M\"},{\"name\":\"Jane\",\"age\":\"20\"},{}]}";
JsonObject object = new JsonParser().parse(companyJson).getAsJsonObject();
System.out.println("========== Encrypt Value =========");
companyJson = cipherValue(object, true);
System.out.println(companyJson);
System.out.println("========== Decrypt Value =========");
companyJson = cipherValue(object, false);
System.out.println(companyJson);
}
/**
* Encrypt OR Decript Method
* @param jsonObject
* @param isEncrypt true: encrypt false: decrypt
* @return
*/
private static String cipherValue(JsonObject jsonObject, boolean isEncrypt) {
Iterator<Map.Entry<String, JsonElement>> iterator = jsonObject.entrySet().iterator();
Map.Entry<String, JsonElement> entry;
while (iterator.hasNext()) {
entry = iterator.next();
JsonElement value = entry.getValue();
if (value.isJsonPrimitive()) {
try {
if (isEncrypt) {
entry.setValue(new JsonPrimitive(EncryptSDK.encData(entry.getValue().getAsString())));
} else {
entry.setValue(new JsonPrimitive(EncryptSDK.decrypt(entry.getValue().getAsString())));
}
} catch (Exception e) {}
} else if (value.isJsonObject()) {
cipherValue(value.getAsJsonObject(), isEncrypt);
} else if (value.isJsonArray()) {
JsonArray jsonArray = value.getAsJsonArray();
JsonElement jsonElement;
for (int i = 0; i < jsonArray.size(); i++) {
jsonElement = jsonArray.get(i);
cipherValue(jsonElement.getAsJsonObject(), isEncrypt);
}
}
}
return jsonObject.toString();
}
}
결과
{"name":"65bd107f32a622fc\u0000\u0000\u0000\u0015¡??\u0015\u0003¾?[??Þ???b??[}\nU(ß\u0005?I;ºjØ\tÐ\rðÞÆøt´?Vi?´c952c26628af4204","employees":[{"name":"65bd107f32a622fc\u0000\u0000\u0000\u000bh\u000e\u001f???\u0015???\b/?¼\n ??°DAx¿¶p?¿¶c952c26628af4204","age":"65bd107f32a622fc\u0000\u0000\u0000\u0002h\u000e\u001f???\u0015???\b/\f?,\u0006¤Kq?\"?^\u0011¸?\u000e?c952c26628af4204","sex":"65bd107f32a622fc\u0000\u0000\u0000\u0001h\u000e\u001f???\u0015???\b/?wH\u001c?þE?\u0011¼?B\u0002\u0007??c952c26628af4204"},{"name":"65bd107f32a622fc\u0000\u0000\u0000\u0005???[e??\tv/6?T\rÐ%G??\u0003Np?k???c952c26628af4204","age":"65bd107f32a622fc\u0000\u0000\u0000\u0002???[e??\tv/6?\u000b?±??\u0002m??,N??gºc952c26628af4204","sex":"65bd107f32a622fc\u0000\u0000\u0000\u0001???[e??\tv/6?wH\u001c?þE?\u0011¼?B\u0002\u0007??c952c26628af4204"},{"name":"65bd107f32a622fc\u0000\u0000\u0000\u0004???[e??\tv/6½¸ª)?3??NR??],.c952c26628af4204","sex":"65bd107f32a622fc\u0000\u0000\u0000\u0001???[e??\tv/6?wH\u001c?þE?\u0011¼?B\u0002\u0007??c952c26628af4204"},{"name":"65bd107f32a622fc\u0000\u0000\u0000\u0004\u0000L?.l6\u0015??pv?½??{?\u0004?\u0017D?÷´T?²?c952c26628af4204","age":"65bd107f32a622fc\u0000\u0000\u0000\u0002\u0000L?.l6\u0015??pv?M$N??L]·??±?qm?c952c26628af4204"},{}]}
========== Decrypt Value =========
{"name":"1004lucifer's Company","employees":[{"name":"1004lucifer","age":"30","sex":"M"},{"name":"vvoei","age":"29","sex":"M"},{"name":"John","sex":"M"},{"name":"Jane","age":"20"},{}]}
Gson 에서의 기본적인 Element는 JsonElement 이다.
JsonElement 가 JSON 값(Value)에 해당이 되며 JSON 값의 종류는 다음과 같다.
1004lucifer
1. Array
- "[]" 과 같은 경우를 말한다.
- Array 에는 Null 과 Object 둘중의 하나의 값이 들어가 있다.
1) Null : []
2) Object: [{"a":"b"},{"c","d"}]
2. Null
- 있는 그대로 Null 이다.
- {} <= 이것은 Null 이 아니라 값이 비어있는 Object 이다.
3. Object
- "{}" 로 처리되는 구문이 Object 로 취급된다.
4. Primitive
- Object 와 다른 부분은 순수(primitive)값 이라는 부분에서 차이가 있다.
- Boolean, String, Int, Double, Float 등등 일반적으로 사용하는 값들이 해당된다.
- ex) {"a": "aa", "b": "123", "c": "12.3", "d": {}, "e": [{"b": "bb"}]}
JsonElement 를 상속받은 Subclass 로는 다음이 있다.
1. JsonArray
2. JsonNull
3. JsonObject
4. JsonPrimitive
2. JsonNull
3. JsonObject
4. JsonPrimitive
JavaObject 가 없는 상황에서 JSON 값을 편집하려 하면 JsonElement 의 Subclass 들을 활용해서 값을 받아오고 수정해야 한다.
(2위의 2번째 예제와 같이..)
1004lucifer
만일 가져올 값이 미리 정해져 있고 특정 값만 가져온다고 하면 다음의 Method 를 사용해서 값을 가져올 수 있다.
JsonObject
JsonElement | get(String memberName)Returns the member with the specified name. |
JsonArray | getAsJsonArray(String memberName)Convenience method to get the specified member as a JsonArray. |
JsonObject | etAsJsonObject(String memberName)Convenience method to get the specified member as a JsonObject. |
JsonPrimitive | getAsJsonPrimitive(String memberName)Convenience method to get the specified member as a JsonPrimitive element. |
단순한 JSON이라면 상관 없겠지만 Depth가 있는 JSON 이라면 Depth를 따라 찾아야 한다.
1004lucifer
만일 아래의 JSON 에서 bb 의 55555 라는 값을 가지고 오고 싶다면 다음과 같이 사용하면 된다.
{"a": "aa", "b": "123", "c": "12.3", "d": {}, "e": [{"bb": "55555"}]}
TestGsonString.java
import com.google.gson.*;
/**
* Created by 1004lucifer on 2015-04-08.
*/
public class TestGsonString {
public static void main(String[] argv) {
String companyJson= "{\"a\": \"aa\", \"b\": \"123\", \"c\": \"12.3\", \"d\": {}, \"e\": [{\"bb\": \"55555\"}]}";
JsonObject jsonObject = new JsonParser().parse(companyJson).getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray("e");
JsonObject jsonObject1 = jsonArray.get(0).getAsJsonObject();
JsonPrimitive jsonPrimitive = jsonObject1.getAsJsonPrimitive("bb");
int value = jsonPrimitive.getAsInt();
System.out.println("value == 55555 is : " + (value == 55555));
}
}
결과
이정도만 알아도 Java 에서 JSON 처리를 어느정도 할 수 있지 않을까 싶다.
댓글
댓글 쓰기