Gson
기본적으로 class 를 만나면 primitive 값들을 json 으로 표현해 준다. 이 serialized json 의 format 이나 값을 바꾸고 싶다면 직접 JsonSerializer 를 만들어서 이 만든 JsonSerializer 를 GsonBuilder 를 이용해 등록 해 주면 된다.Source codes
Body
public class Body<T> {
public String bodyType = "ok";
public T key;
public KeyType2 key2;
public void setKey(T key) {
this.key = key;
}
public void setKey2(KeyType2 key2) {
this.key2 = key2;
}
public T get() {
return key;
}
}
KeyType1
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
public class KeyType1 {
private String key;
public KeyType1(String key) {
this.key = key;
}
public String getKey() {
return key;
}
public static class KeyType1Serializer implements JsonSerializer<KeyType1> {
@Override
public JsonElement serialize(KeyType1 src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject object = new JsonObject();
String name = src.getKey().replaceAll(" ", "_");
object.addProperty("name", name);
return object;
}
}
}
KeyType2
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
public class KeyType2 {
private String key;
public KeyType2(String key) {
this.key = key;
}
public String getKey() {
return key;
}
public static class KeyType2Serializer implements JsonSerializer<KeyType2> {
@Override
public JsonElement serialize(KeyType2 src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject object = new JsonObject();
String name = src.getKey().replaceAll(" ", "_");
object.addProperty("name", name);
return object;
}
}
}
main
public static void main(String[] args) {
Body<KeyType1> body = new Body<KeyType1>();
KeyType1 key = new KeyType1("I am a dog");
body.setKey(key);
body.setKey2(new KeyType2("cat"));
Gson gson = new GsonBuilder()
.registerTypeAdapter(KeyType1.class, new KeyType1.KeyType1Serializer())
.registerTypeAdapter(KeyType2.class, new KeyType2.KeyType2Serializer())
.setPrettyPrinting().create();
// Since Animal contains generic type create the type using TypeToken
// class.
Type bodyType = new TypeToken<Body<KeyType1>>() {
}.getType();
System.out.println(gson.toJson(body, bodyType));
}
Download codes
source 는 아래에서 다운로드 할 수 있다.이 source 는 gradle 로 되어 있어서 아래처럼 하면 compile 을 해 볼 수 있다.(참고 gradle 사용법)
f:\plainJava> gradlew wrapper ... f:\plainJava> gradlew compileJava
From String
References
- java - Gson Array of Strings to JsonArray - Stack Overflow
- GSON Serialiser Example | Java Creed
- GSON Annotations Example | Java Creed
- Exclude fields from JSON with java modifiers using Gson | Camelcode.org
댓글 없음:
댓글 쓰기