随笔 - 1357  文章 - 0  评论 - 1104  阅读 - 1941万

JSON与JAVA数据的相互转换

复制代码
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;


/**
* json对象转换为java对象
*
*
@throws JSONException
*/
@Test
public void jsonToJava(){
String json="[{\"addTime\":\"2011-09-19 14:23:02\",\"iccid\":\"1111\",\"id\":0,\"imei\":\"2222\",\"imsi\":\"3333\",\"phoneType\":\"4444\",\"remark\":\"aaaa\",\"tel\":\"5555\"}]";
//接收{}对象,此处接收数组对象会有异常
if(json.indexOf("[")!=-1){
json=json.replace("[", "");
}
if(json.indexOf("]")!=-1){
json=json.replace("]", "");
}
JSONObject obj=new JSONObject().fromObject(json);
SimInfo simInfo=(SimInfo)JSONObject.toBean(obj, SimInfo.class);
System.out.println("obj: "+simInfo);
System.out.println(simInfo.getAddTime());
System.out.println(simInfo.getIccid());
System.out.println(simInfo.getImei());
System.out.println(simInfo.getImsi());
System.out.println(simInfo.getPhoneType());
System.out.println(simInfo.getRemark());
System.out.println(simInfo.getTel());
System.out.println(simInfo.getId());

DaoFactory.getSimInfoDao().add(simInfo);
}

/**
* 将json转换为java集合对象
*/
@Test
public void jsonToJavas(){
String jsons="[{\"addTime\":\"2011-09-19 14:23:02\",\"iccid\":\"1111\",\"id\":0,\"imei\":\"2222\",\"imsi\":\"3333\",\"phoneType\":\"4444\",\"remark\":\"aaaa\",\"tel\":\"5555\"}," +
"{\"addTime\":\"2011-11-11 14:23:02\",\"iccid\":\"2222\",\"id\":0,\"imei\":\"2222\",\"imsi\":\"3333\",\"phoneType\":\"4444\",\"remark\":\"aaaa\",\"tel\":\"5555\"}]";
List<SimInfo> simInfos = getJavaCollection(new SimInfo(),jsons);
System.out.println(simInfos.size());
for(SimInfo simInfo:simInfos){
System.out.println("addTime: "+simInfo.getAddTime());
System.out.println("=========");
}

}

/**
* 封装将json对象转换为java集合对象
*
*
@param <T>
*
@param clazz
*
@param jsons
*
@return
*/
private <T> List<T> getJavaCollection(T clazz, String jsons) {
List<T> objs=null;
JSONArray jsonArray=(JSONArray)JSONSerializer.toJSON(jsons);
if(jsonArray!=null){
objs=new ArrayList<T>();
List list=(List)JSONSerializer.toJava(jsonArray);
for(Object o:list){
JSONObject jsonObject=JSONObject.fromObject(o);
T obj=(T)JSONObject.toBean(jsonObject, clazz.getClass());
objs.add(obj);
}
}
return objs;
}

/**
* java对象转换为json对象
*
*
@throws JSONException
*/
@Test
public void javaToJson(){
SimInfo simInfo=new SimInfo();
simInfo.setAddTime(UtilTool.dateToStr(new Date(), null));
simInfo.setIccid("1111");
simInfo.setImei("2222");
simInfo.setImsi("3333");
simInfo.setPhoneType(4);
simInfo.setRemark("aaaa");
simInfo.setTel("5555");
//java对象转换为json对象
String json=new JSONArray().fromObject(simInfo).toString();
//json: [{"addTime":"2011-09-19 14:23:02","iccid":"1111","id":0,"imei":"2222","imsi":"3333","phoneType":"4444","remark":"aaaa","tel":"5555"}]
System.out.println("json: "+json);
}
复制代码


         

jackson-core-asl-1.7.2.jar   

jackson-mapper-asl-1.7.2.jar

            //将一个Java对象转换成JSON
StringWriter writer = new StringWriter();
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(writer, simInfo);
String json=writer.toString();

           

           

复制代码
基于json-lib.jar包Json实例程序
1.JSONObject to DynaBean
String json = "{name=\"json\",bool:true,int:1,double:2.2}";
JSONObject jsonObject = JSONObject.fromObject(json);
//抽象的写法:DynaBean bean = (DynaBean) JSONSerializer.toJava( jsonObject );
Object bean = JSONObject.toBean(jsonObject);
//Object bean1 = JSONSerializer.toJava(jsonObject);
assertEquals(jsonObject.get("name"), PropertyUtils.getProperty(bean, "name"));
assertEquals(jsonObject.get("bool"), PropertyUtils.getProperty(bean, "bool"));
assertEquals(jsonObject.get("int"), PropertyUtils.getProperty(bean, "int"));
assertEquals(jsonObject.get("double"), PropertyUtils.getProperty(bean, "double"));

2.JSONObject to JavaBean
String json = "{name:\"zhangsan\",age:25,hight:1.72,sex:true}";
JSONObject jsonObject = JSONObject.fromObject(json);
UserBean bean = (UserBean) JSONObject.toBean(jsonObject, UserBean.class);
System.out.println(jsonObject);
理论上,这样就可以了,但时,有异常Caused by: java.lang.NoSuchMethodException: com.json.Json$UserBean.<init>()
             
3.JSONArray to List
String json = "[\"first\",\"second\"]";
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(json);
List output = (List) JSONSerializer.toJava(jsonArray);

4.JSONArray to array
String json = "[\"first\",\"second\"]";
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(json);
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setArrayMode(JsonConfig.MODE_OBJECT_ARRAY);
Object[] output = (Object[]) JSONSerializer.toJava(jsonArray, jsonConfig);
Object[] expected = new Object[] { "first", "second" };
ArrayAssertions.assertEquals(expected, output);

5.JSON 字符串 专为 JavaBean(刘慧斌demo 演示需要的jar包在附件里)

String str="[{\"id\":\"328\",\"mestype\":\"inbox\"},{\"id\":\"327\",\"mestype\":\"inbox\"},{\"id\":\"279\",\"mestype\":\"already\"},{\"id\":\"278\",\"mestype\":\"already\"},{\"id\":\"277\",\"mestype\":\"already\"},{\"id\":\"310\",\"mestype\":\"inbox\"},{\"id\":\"308\",\"mestype\":\"inbox\"},{\"id\":\"305\",\"mestype\":\"inbox\"},{\"id\":\"304\",\"mestype\":\"inbox\"},{\"id\":\"303\",\"mestype\":\"inbox\"}]";
JSONArray jsonArray=(JSONArray) JSONSerializer.toJSON(str);
List list=(List)JSONSerializer.toJava(jsonArray);
for (Object obj: list) {
JSONObject jsonObject = JSONObject.fromObject(obj);
MessageBean bean = (MessageBean) JSONObject.toBean(jsonObject, MessageBean.class);
String id=bean.getId()+"";
String type=bean.getMestype();
System.out.println(id+" "+type);
}
System.out.println(list.size());
复制代码




posted on   Ruthless  阅读(70085)  评论(8编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
< 2011年9月 >
28 29 30 31 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 1
2 3 4 5 6 7 8

点击右上角即可分享
微信分享提示