This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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