카테고리 없음
[펌] Gson.fromJson(..)으로 Map 변환 시 Integer 형이 Double 형으로 바뀌는 문제 해결
Yizi
2017. 11. 10. 11:27
출처 : https://okky.kr/article/371438
Custom Deserializer 클래스 (999 -> 999.0 과 같은 Number 자동 변환 방지)
package mltm.com.customize.configure;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
public class HashMapDeserializer implements JsonDeserializer> {
@Override
public HashMap deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) throws JsonParseException {
JsonObject obj = json.getAsJsonObject();
Entry entry = obj.entrySet().iterator().next();
HashMap resultMap = new HashMap();
resultMap.put(entry.getKey(), ParseObjectFromElement.SINGLETON.apply(entry.getValue()));
return resultMap;
}
public enum ParseObjectFromElement implements Function {
SINGLETON;
public Object apply(JsonElement input) {
Object value = null;
if (input == null || input.isJsonNull()) {
value = null;
} else if (input.isJsonPrimitive()) {
JsonPrimitive primitive = input.getAsJsonPrimitive();
if (primitive.isNumber()) {
value = primitive.getAsInt(); // Number 값은 무조건 integer로 처리
} else if (primitive.isBoolean()) {
value = primitive.getAsBoolean();
} else {
value = primitive.getAsString();
}
} else if (input.isJsonArray()) {
value = Lists.newArrayList(Iterables.transform(input.getAsJsonArray(), this));
} else if (input.isJsonObject()) {
value = Maps. newLinkedHashMap(
Maps.transformValues(JsonObjectAsMap.INSTANCE.apply(input.getAsJsonObject()), this));
}
return value;
}
}
public enum JsonObjectAsMap implements Function> {
INSTANCE;
private final Field members;
JsonObjectAsMap() {
try {
members = JsonObject.class.getDeclaredField("members");
members.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new UnsupportedOperationException("cannot access gson internals", e);
}
}
@SuppressWarnings("unchecked")
@Override
public Map apply(JsonObject in) {
try {
return (Map) members.get(in);
} catch (IllegalArgumentException e) {
throw new UnsupportedOperationException("cannot access gson internals", e);
} catch (IllegalAccessException e) {
throw new UnsupportedOperationException("cannot access gson internals", e);
}
}
}
}
custom Deserializer를 이용하여 gson 객체 생성
Gson gson = new GsonBuilder().registerTypeAdapter(HashMap.class, new HashMapDeserializer()).create();
json convert to tree linked map
Map<String, Object> retMap = gson.fromJson(jsonData, new TypeToken<HashMap<String, Object>>() {}.getType());
결과
위와 같은 xml 데이터를
위처럼 json 형태로 변환한 다음
tree map 형태로 최종 변환 합니다.
출처 : https://okky.kr/article/371438
해당 게시글 원작자이신 okky 오로롱이님 감사합니다.