Skip to content

Instantly share code, notes, and snippets.

@geminiwen
Created August 26, 2015 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geminiwen/833b63199355753e5e78 to your computer and use it in GitHub Desktop.
Save geminiwen/833b63199355753e5e78 to your computer and use it in GitHub Desktop.
package com.segmentfault.app.utils.json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.annotation.JSONField;
import org.json.JSONObject;
import java.lang.reflect.Field;
import java.util.Iterator;
/**
* Created by geminiwen on 15/4/9.
*/
public class JSONUtil {
public static <T> T readValue(String content, TypeReference<T> type) {
return JSON.parseObject(content, type);
}
public static String writeValue(Object obj) {
return JSON.toJSONString(obj);
}
public static <T> T decodeJSONObject(JSONObject jsonObject, Class<T> clazz) {
T instance = null;
try {
instance = clazz.newInstance();
Iterator<String> keys = jsonObject.keys();
Field[] fields = clazz.getDeclaredFields();
for(;keys.hasNext();) {
String key = keys.next();
for (Field field: fields) {
if (field.isAnnotationPresent(JSONField.class)) {
JSONField jsonField = field.getAnnotation(JSONField.class);
String jsonFieldName = jsonField.name();
if (!jsonFieldName.equals(key)) {
continue;
}
if (!jsonField.deserialize()) {
break;
}
Object obj = jsonObject.opt(key);
field.setAccessible(true);
field.set(instance, obj);
break;
}
if (field.getName().equals(key)) {
Object obj = jsonObject.opt(key);
field.setAccessible(true);
field.set(instance, obj);
break;
}
}
}
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
}
return instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment