JAVA解析JSON相关
在网上看了好些JAVA解析JSON文章,感觉很不错,直接收为私用了:
一json-lib.jar开发包使用依赖包
json-lib.jar开发包使用需要依赖包以下开发包:
Json-librequires(atleast)thefollowingdependenciesinyourclasspath:
*jakartacommons-lang2.4
*jakartacommons-beanutils1.7.0
*jakartacommons-collections3.2
*jakartacommons-logging1.1.1
*jakartajson-lib-2.4-jdk15.jar
*ezmorph1.0.6
.二.
publicclassJsonUtil{
/**页面传至后台时,json数据在request的参数名称*/
publicfinalstaticStringJSON_ATTRIBUTE="json";
publicfinalstaticStringJSON_ATTRIBUTE1="json1";
publicfinalstaticStringJSON_ATTRIBUTE2="json2";
publicfinalstaticStringJSON_ATTRIBUTE3="json3";
publicfinalstaticStringJSON_ATTRIBUTE4="json4";
/**
*从一个JSON对象字符格式中得到一个java对象,形如:
*{"id":idValue,"name":nameValue,"aBean":{"aBeanId":aBeanIdValue,...}}
*@paramobject
*@paramclazz
*@return
*/
publicstaticObjectgetDTO(StringjsonString,Classclazz){
JSONObjectjsonObject=null;
try{
setDataFormat2JAVA();
jsonObject=JSONObject.fromObject(jsonString);
}catch(Exceptione){
e.printStackTrace();
}
returnJSONObject.toBean(jsonObject,clazz);
}
/**
*从一个JSON对象字符格式中得到一个java对象,其中beansList是一类的集合,形如:
*{"id":idValue,"name":nameValue,"aBean":{"aBeanId":aBeanIdValue,...},
*beansList:[{},{},...]}
*@paramjsonString
*@paramclazz
*@parammap集合属性的类型(key:集合属性名,value:集合属性类型class)eg:("beansList":Bean.class)
*@return
*/
publicstaticObjectgetDTO(StringjsonString,Classclazz,Mapmap){
JSONObjectjsonObject=null;
try{
setDataFormat2JAVA();
jsonObject=JSONObject.fromObject(jsonString);
}catch(Exceptione){
e.printStackTrace();
}
returnJSONObject.toBean(jsonObject,clazz,map);
}
/**
*从一个JSON数组得到一个java对象数组,形如:
*[{"id":idValue,"name":nameValue},{"id":idValue,"name":nameValue},...]
*@paramobject
*@paramclazz
*@return
*/
publicstaticObject[]getDTOArray(StringjsonString,Classclazz){
setDataFormat2JAVA();
JSONArrayarray=JSONArray.fromObject(jsonString);
Object[]obj=newObject[array.size()];
for(inti=0;i<array.size();i++){
JSONObjectjsonObject=array.getJSONObject(i);
obj[i]=JSONObject.toBean(jsonObject,clazz);
}
returnobj;
}
/**
*从一个JSON数组得到一个java对象数组,形如:
*[{"id":idValue,"name":nameValue},{"id":idValue,"name":nameValue},...]
*@paramobject
*@paramclazz
*@parammap
*@return
*/
publicstaticObject[]getDTOArray(StringjsonString,Classclazz,Mapmap){
setDataFormat2JAVA();
JSONArrayarray=JSONArray.fromObject(jsonString);
Object[]obj=newObject[array.size()];
for(inti=0;i<array.size();i++){
JSONObjectjsonObject=array.getJSONObject(i);
obj[i]=JSONObject.toBean(jsonObject,clazz,map);
}
returnobj;
}
/**
*从一个JSON数组得到一个java对象集合
*@paramobject
*@paramclazz
*@return
*/
publicstaticListgetDTOList(StringjsonString,Classclazz){
setDataFormat2JAVA();
JSONArrayarray=JSONArray.fromObject(jsonString);
Listlist=newArrayList();
for(Iteratoriter=array.iterator();iter.hasNext();){
JSONObjectjsonObject=(JSONObject)iter.next();
list.add(JSONObject.toBean(jsonObject,clazz));
}
returnlist;
}
/**
*从一个JSON数组得到一个java对象集合,其中对象中包含有集合属性
*@paramobject
*@paramclazz
*@parammap集合属性的类型
*@return
*/
publicstaticListgetDTOList(StringjsonString,Classclazz,Mapmap){
setDataFormat2JAVA();
JSONArrayarray=JSONArray.fromObject(jsonString);
Listlist=newArrayList();
for(Iteratoriter=array.iterator();iter.hasNext();){
JSONObjectjsonObject=(JSONObject)iter.next();
list.add(JSONObject.toBean(jsonObject,clazz,map));
}
returnlist;
}
/**
*从jsonHASH表达式中获取一个map,该map支持嵌套功能
*形如:{"id":"johncon","name":"小强"}
*注意commons-collections版本,必须包含org.apache.commons.collections.map.MultiKeyMap
*@paramobject
*@return
*/
publicstaticMapgetMapFromJson(StringjsonString){
setDataFormat2JAVA();
JSONObjectjsonObject=JSONObject.fromObject(jsonString);
Mapmap=newHashMap();
for(Iteratoriter=jsonObject.keys();iter.hasNext();){
Stringkey=(String)iter.next();
map.put(key,jsonObject.get(key));
}
returnmap;
}
/**
*从json数组中得到相应java数组
*json形如:["123","456"]
*@paramjsonString
*@return
*/
publicstaticObject[]getObjectArrayFromJson(StringjsonString){
JSONArrayjsonArray=JSONArray.fromObject(jsonString);
returnjsonArray.toArray();
}
/**
*把数据对象转换成json字符串
*DTO对象形如:{"id":idValue,"name":nameValue,...}
*数组对象形如:[{},{},{},...]
*map对象形如:{key1:{"id":idValue,"name":nameValue,...},key2:{},...}
*@paramobject
*@return
*/
publicstaticStringgetJSONString(Objectobject)throwsException{
StringjsonString=null;
//日期值处理器
JsonConfigjsonConfig=newJsonConfig();
jsonConfig.registerJsonValueProcessor(java.util.Date.class,newJsonDateValueProcessor());
if(object!=null){
if(objectinstanceofCollection||objectinstanceofObject[]){
jsonString=JSONArray.fromObject(object,jsonConfig).toString();
}else{
jsonString=JSONObject.fromObject(object,jsonConfig).toString();
}
}
returnjsonString==null?"{}":jsonString;
}
privatestaticvoidsetDataFormat2JAVA(){
//设定日期转换格式
JSONUtils.getMorpherRegistry().registerMorpher(newDateMorpher(newString[]{"yyyy-MM-dd","yyyy-MM-ddHH:mm:ss"}));
}
publicstaticvoidmain(String[]arg)throwsException{
Strings="{status:'success'}";
System.out.println("object:"+JsonUtil.getJSONString(s));
}
}
importjava.text.SimpleDateFormat;
importjava.util.Date;
importnet.sf.json.JsonConfig;
importnet.sf.json.processors.JsonValueProcessor;
/*
*@authorjohncon
*创建日期2008-9-10
*json日期值处理器
*/
publicclassJsonDateValueProcessorimplementsJsonValueProcessor{
privateStringformat="yyyy-MM-ddHH:mm:ss";
publicJsonDateValueProcessor(){
}
三解析如下例子
StringrowidString="[{\"kl_id\":\"2\",\"kl_title\":\"Testdate\",\"kl_content\":\"Testdate\",\"kl_type\":\"1\",\"id\":\"1\"},{\"kl_id\":\"2\",\"kl_title\":\"Test\",\"kl_content\":\"Test\",\"kl_type\":\"1\",\"id\":\"2\"}]";
JSONArrayarray=JSONArray.fromObject(rowidString);
Object[]obj=newObject[array.size()];
for(inti=0;i<array.size();i++){
JSONObjectjsonObject=array.getJSONObject(i);
System.out.println(jsonObject.get("kl_id"));
}
publicJsonDateValueProcessor(Stringformat){
this.format=format;
}
publicObjectprocessArrayValue(Objectvalue,JsonConfigjsonConfig){
returnprocess(value,jsonConfig);
}
publicObjectprocessObjectValue(Stringkey,Objectvalue,JsonConfigjsonConfig){
returnprocess(value,jsonConfig);
}
privateObjectprocess(Objectvalue,JsonConfigjsonConfig){
if(valueinstanceofDate){
Stringstr=newSimpleDateFormat(format).format((Date)value);
returnstr;
}
returnvalue==null?null:value.toString();
}
publicStringgetFormat(){
returnformat;
}
publicvoidsetFormat(Stringformat){
this.format=format;
}
}
对于对象中有明确类型的对象属性,可不管;但对象中有集合属性的,由于类型不明确,所以要先明确类型:
StringjsonString=request.getParameter("json");
//增加对象中的集合属性的类型以及对象元素中的对象属性的集合属性的类型
MapclazzMap=newHashMap();
//secondItems是FirstDTO里的集合属性
clazzMap.put("secondItems",SecondDTO.class);
//thirdItems是SecondDTO里的集合属性
clazzMap.put("thirdItems",ThirdDTO.class);
FirstDTOfirstDTO=(FirstDTO)JsonUtil.getDTO(jsonString,FirstDTO.class,clazzMap);