일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
- FIDO2
- 애플
- apple
- 앱리소스
- OSX
- openssl
- WebAuthn
- otpkey
- appres
- fido
- OTP
- 앱스토어
- MSYS2
- git
- SSL
- SSH
- SwiftUI
- albumbook
- Android
- 앨범북
- Xcode
- MFA
- 인증
- 2FA
- MYSQL
- 안드로이드
- kmip
- Nodejs
- SWIFT
- css
- Today
- Total
인디노트
Google Library 중에 하나인 Gson 본문
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | 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
JsonElement 를 상속받은 Subclass 로는 다음이 있다.
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 | getAsJsonObject(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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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 처리를 어느정도 할 수 있지 않을까 싶다.
'소스 팁 > Java, Android, Kotlin' 카테고리의 다른 글
Android External SD Card Access from Lollipop (0) | 2017.03.19 |
---|---|
Android External SD Card Access (0) | 2017.03.19 |
Activity 생성시에 사용되는 Intent Flag 정리 (0) | 2017.01.11 |
Activity 생성시 Intent Flag (0) | 2017.01.10 |
안드로이드 Bitmap Utility(resize, crop) 클래스 (0) | 2016.11.12 |