json解析,其实也可以说是转换,其他的不多说了,我目前不是很清楚深层的原理,毕竟一般来说本人秉着先用后理解的方式哈,下边是简单的使用的小例子。
1、gson
jar包:
UtrRealIdentify utrRealIdentify = new UtrRealIdentify();//我自己的类
utrRealIdentify.setIsOk("this is ok");//简单的赋个值,
Gson gsonData = new GsonBuilder().create();//定义gson对象
String jsonstr = gsonData .toJson(utrRealIdentify);//为了看效果,所以我先把对象转成json,下边在转换回来,如果直接有json类型的数来直接使用的话就不用转换这步。
System.out.println(jsonstr);//{"isOk":"this is ok"}
System.out.println(utrRealIdentify.getIsOk());//this is ok
utrRealIdentify.setIsOk("this is ok");//简单的赋个值,
ObjectMapper mapper = new ObjectMapper(); // ObjectMapper支持从byte[]、File、InputStream、字符串等数据的JSON反序列化。
String jsonstr = mapper.writeValueAsString(utrRealIdentify);//对象转成jsonSystem.out.println(jsonstr);//{"isOk":"this is ok"}
utrRealIdentify = mapper.readValue(jsonstr, UtrRealIdentify.class);//解析json数据,转成java类
System.out.println(utrRealIdentify.getIsOk());//this is ok
3、fastjson
jar包:
UtrRealIdentify utrRealIdentify =new UtrRealIdentify();
utrRealIdentify.setIsOk("this is ok");//简单的赋个值,
String jsonstr =JSON.toJSONString(utrRealIdentify);//对象转成json
System.out.println(jsonstr);//{"isOk":"this is ok"}
utrRealIdentify =JSON.parseObject(jsonstr, UtrRealIdentify.class);//解析json数据,转成java类
System.out.println(utrRealIdentify.getIsOk());//this is ok