首页 > 代码库 > gson和fastjson将json对象转换成javaBean 简单对照
gson和fastjson将json对象转换成javaBean 简单对照
同事离职,项目后端部分的迭代和重构后面由我接手.
今天看项目代码时,发现项目使用了Gson,用于将json字符串转换成javaBean.
以前没使用过Gson,随即,简单入了个们,
想起fastjson也有将json字符串转换成javaBean的API,随即简单比较了下源码.
fastjson中的API如下:
/**
* @since 1.2.9
*/
public <T> T toJavaObject(Class<T> clazz) {
return TypeUtils.cast(this, clazz, ParserConfig.getGlobalInstance());
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T cast(Object obj, Class<T> clazz, ParserConfig config) {
if (obj == null) {
return null;
}
if (clazz == null) {
throw new IllegalArgumentException("clazz is null");
}
if (clazz == obj.getClass()) {
return (T) obj;
}
if (obj instanceof Map) {
if (clazz == Map.class) {
return (T) obj;
}
Map map = (Map) obj;
if (clazz == Object.class && !map.containsKey(JSON.DEFAULT_TYPE_KEY)) {
return (T) obj;
}
return castToJavaBean((Map<String, Object>) obj, clazz, config);
}
if (clazz.isArray()) {
if (obj instanceof Collection) {
Collection collection = (Collection) obj;
int index = 0;
Object array = Array.newInstance(clazz.getComponentType(), collection.size());
for (Object item : collection) {
Object value = http://www.mamicode.com/cast(item, clazz.getComponentType(), config);"can not cast to : " + clazz.getName(), e);
}
}
calendar.setTime(date);
return (T) calendar;
}
if (obj instanceof String) {
String strVal = (String) obj;
if (strVal.length() == 0 //
|| "null".equals(strVal) //
|| "NULL".equals(strVal)) {
return null;
}
if (clazz == java.util.Currency.class) {
return (T) java.util.Currency.getInstance(strVal);
}
}
throw new JSONException("can not cast to : " + clazz.getName());
}
@SuppressWarnings({ "unchecked" })
public static <T> T castToJavaBean(Map<String, Object> map, Class<T> clazz, ParserConfig config) {
try {
if (clazz == StackTraceElement.class) {
String declaringClass = (String) map.get("className");
String methodName = (String) map.get("methodName");
String fileName = (String) map.get("fileName");
int lineNumber;
{
Number value = http://www.mamicode.com/(Number) map.get("lineNumber");
if (value =http://www.mamicode.com/= null) {" not found");
}
if (!loadClazz.equals(clazz)) {
return (T) castToJavaBean(map, loadClazz, config);
}
}
}
if (clazz.isInterface()) {
JSONObject object;
if (map instanceof JSONObject) {
object = (JSONObject) map;
} else {
object = new JSONObject(map);
}
return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
new Class<?>[] { clazz }, object);
}
if (config == null) {
config = ParserConfig.getGlobalInstance();
}
JavaBeanDeserializer javaBeanDeser = null;
ObjectDeserializer deserizer = config.getDeserializer(clazz);
if (deserizer instanceof JavaBeanDeserializer) {
javaBeanDeser = (JavaBeanDeserializer) deserizer;
}
if (javaBeanDeser == null) {
throw new JSONException("can not get javaBeanDeserializer");
}
return (T) javaBeanDeser.createInstance(map, config);
} catch (Exception e) {
throw new JSONException(e.getMessage(), e);
}
}
简单捋了一遍,看到代码中标黄的部分代码,可知,是利用反射原理来获得javaBean的.
如下,为Gson的demo:
1 package cn.code.gson; 2 3 import java.io.*; 4 5 import java.util.Map; 6 7 import com.google.gson.Gson; 8 import com.google.gson.GsonBuilder; 9 10 import cn.code.entity.Person; 11 12 /** 13 * Created by zq on 2017/6/16. 14 */ 15 public class GsonTest { 16 17 /** 18 * @param args 主函数形参 19 */ 20 public static void main(String[] args) { 21 Gson gson = new GsonBuilder().create(); 22 23 gson.toJson("Hello", System.out); 24 gson.toJson("123", System.out); 25 System.out.println(); 26 27 // try (Writer writer = new FileWriter("d:\\gson.txt")) { 28 // gson.toJson("Hello", writer); 29 // gson.toJson("123", writer); 30 // } catch (IOException e) { 31 // e.printStackTrace(); 32 // } 33 FileInputStream fileInputStream = null; 34 35 try { 36 fileInputStream = new FileInputStream("d:\\gson.txt"); 37 } catch (FileNotFoundException e) { 38 e.printStackTrace(); 39 } 40 41 Person person = getJavaBean(fileInputStream); 42 43 System.out.println(person); 44 } 45 46 /** 47 * 48 * @param fileInputStream 根据附件字节流 返回java类 49 * @return 50 */ 51 public static Person getJavaBean(FileInputStream fileInputStream) { 52 Gson gson = new GsonBuilder().create(); 53 Person person = null; 54 55 try (Reader reader = new InputStreamReader(fileInputStream)) { 56 person = gson.fromJson(reader, Person.class); 57 } catch (FileNotFoundException e) { 58 e.printStackTrace(); 59 } catch (IOException e) { 60 e.printStackTrace(); 61 } 62 63 return person; 64 } 65 } 66 67 68 //~ Formatted by Jindent --- http://www.jindent.com
gson和fastjson将json对象转换成javaBean 简单对照
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。