json格式转换成javaBean对象的方法

失落夏天
Android领域优质创作者
博客专家认证
2013-01-05 05:24:34
前几天做京东接口的时候,京东给我返回的结果都是以json的形式返回的。刚开始很头痛,都是以str接受然后转发到html页面上直接打出来解决的。
后来想想是不能这么解决的,这样只能看结果,而不能处理结果集。
所以得把json格式转换成javaBean才可以。
于是查了一下资料,网上最多的资料就是下面的这种方式:

String str = "[{\"id\":\"\",\"num\":\"\",\"dt\":\"2010-07-21T17:29:28\",\"consignee\":\"aaaa\",\"bank\":\"001\",\"ems\":\"0\"}]";
JSONArray array = JSONArray.fromObject(str);//先读取串数组
Object[] o = array.toArray(); //转成对像数组
System.err.println(o.length);
JSONObject obj = JSONObject.fromObject(o[0]);//再使用JsonObject遍历一个个的对像
Order oo = (Order)obj.toBean(obj,Order.class);//指定转换的类型,但仍需要强制转化-成功
System.err.println(oo.getDt()+","+oo.getConsignee());

String ss = oo.getDt();

需要jar包为:json-lib
但是京东提供的jar包里面我没有找到所需要的类。(不愿额外添加jar包)
于是继续找,终于找到了一个ObjectMapper
继续网上搜了一下这个类用法的例子,有,但是比较少,没有直接可以现成用的。
于是就开始自己尝试各种方法来做例子。
最终花费了2个小时终于尝试出来了一个简单的小例子。和大家分享一下,大手们别喷!~
首先字符串:
String str="{\"student\":[{\"name\":\"leilei\",\"age\":23},{\"name\":\"leilei02\",\"age\":23}]}";

接下来创建的是StudentList类

public class StudentList {
List<Student> student;
public List<Student> getStudent() {
return student;
}

public void setStudent(List<Student> student) {
this.student = student;
}
}

下面是Student类
public class Student {
private String name;
private int age;
//private StudentClass studentClass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

最后测试程序

import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;

public class JsonToJavaBean {
public static void main(String[] args) {
String str="{\"student\":[{\"name\":\"leilei\",\"age\":23},{\"name\":\"leilei02\",\"age\":23}]}";
Student stu = null;
List<Student> list = null;
try {
ObjectMapper objectMapper=new ObjectMapper();
StudentList studentList=objectMapper.readValue(str, StudentList.class);
list=studentList.getStudent();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(Student s:list){
System.out.println(s.getName());
}
}

结果:

leilei
leilei02

成功。。兴奋ing!~
继续尝试一下在student的里面添加班级属性的方法
Class stuclass{
private int classid;
private int gradeid;
}
...全文
85048 26 打赏 收藏 转发到动态 举报
写回复
用AI写文章
26 条回复
切换为时间正序
请发表友善的回复…
发表回复
LJ_liujue 2015-08-19
  • 打赏
  • 举报
回复
引用 9 楼 whz137458 的回复:
楼主,我觉得你建的StudentList类一点作用都没,直接接受数据的时候使用List<Student>不就行了吗?需要那么纠结吗?
建立StudentList类是为了readValue。在转换时有一个标准去转换,那么传出的参数类型也就是StudentList。如果给出的class标准不正确,是无法转换的。
daizhenguo1986 2015-04-25
  • 打赏
  • 举报
回复
daizhenguo1986 2015-04-25
  • 打赏
  • 举报
回复
看看这个贴子http://bbs.csdn.net/topics/390644490?page=1 http://www.json123.com
shuangsw1989 2014-07-04
  • 打赏
  • 举报
回复
很好的参考。。。。。
sdfdsfsfxxx 2014-03-10
  • 打赏
  • 举报
回复
看看。。。。。。。。。。。。。。。
yuanlei_214 2013-12-26
  • 打赏
  • 举报
回复
jackson-mapper-lgpl-1.8.5.jar
cyy298 2013-10-30
  • 打赏
  • 举报
回复
引用 15 楼 tfew123456 的回复:
贴上代码供大家参考 package cn.qtone.mobile.utils; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * 将JSON数据转换为具体的对象 * @author jqp * */ public class JsonUtil { public static <T> T convertToObj(JSONObject jsonObject,Class<T> cla){ if(jsonObject==null) return null; Field[] fb =cla.getDeclaredFields(); T t; try { t = cla.newInstance(); for(int j=0;j<fb.length;j++){ String fieldName = fb[j].getName(); String fieldNameU=fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1); Method method=cla.getMethod("set"+fieldNameU, fb[j].getType()); method.invoke(t, jsonObject.get(fieldName)); } return t; } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static <T> List<T> convertToList(JSONArray jsonArray,Class<T> cla){ List<T> list=new ArrayList<T>(); if(jsonArray==null) return list; try { for(int i=0;i<jsonArray.length();i++){ JSONObject jsonObject = jsonArray.getJSONObject(i); T t=JsonUtil.convertToObj(jsonObject, cla); list.add(t); } } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; } }
如果是这种该怎么办[{'id':'1','uname':'Tom','hobbies':[{'name':'跑步'},{'name':'游泳'}]},{'id':'2','uname':'张三','hobbies':[{'name':'睡觉'},{'name':'聊天'}]}]
cyy298 2013-10-30
  • 打赏
  • 举报
回复
是 org.json包吗? 贴上代码供大家参考 package cn.qtone.mobile.utils; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;
冷小鱼 2013-10-10
  • 打赏
  • 举报
回复
jsonArray.length() 这行有问题的 改为 jsonArray.size()
苦逼IT程序猿 2013-08-30
  • 打赏
  • 举报
回复
tfew123456 2013-08-22
  • 打赏
  • 举报
回复
贴上代码供大家参考 package cn.qtone.mobile.utils; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * 将JSON数据转换为具体的对象 * @author jqp * */ public class JsonUtil { public static <T> T convertToObj(JSONObject jsonObject,Class<T> cla){ if(jsonObject==null) return null; Field[] fb =cla.getDeclaredFields(); T t; try { t = cla.newInstance(); for(int j=0;j<fb.length;j++){ String fieldName = fb[j].getName(); String fieldNameU=fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1); Method method=cla.getMethod("set"+fieldNameU, fb[j].getType()); method.invoke(t, jsonObject.get(fieldName)); } return t; } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static <T> List<T> convertToList(JSONArray jsonArray,Class<T> cla){ List<T> list=new ArrayList<T>(); if(jsonArray==null) return list; try { for(int i=0;i<jsonArray.length();i++){ JSONObject jsonObject = jsonArray.getJSONObject(i); T t=JsonUtil.convertToObj(jsonObject, cla); list.add(t); } } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; } }
tfew123456 2013-08-22
  • 打赏
  • 举报
回复
当时不知道有这样的第三方包,于是俺自己写了一个,其实也挺简单的
浅滩 2013-08-08
  • 打赏
  • 举报
回复
遇到相同的问题,楼主还是需要添加除去json以为的第三方jar,不是特别可取,不过暂时没有找到更好的解决方式
  • 打赏
  • 举报
回复
谷歌GSON轻松搞定
霜烟若梦 2013-05-17
  • 打赏
  • 举报
回复
那问问你,怎么能动态生成 String str="{\"student\":[{\"name\":\"leilei\",\"age\":23},{\"name\":\"leilei02\",\"age\":23}]}"; 这种嵌套格式的json对象呢?
鲫鱼 2013-04-17
  • 打赏
  • 举报
回复
刚好工程中用到,学到了
rome_wu 2013-01-15
  • 打赏
  • 举报
回复
楼主,我觉得你建的StudentList类一点作用都没,直接接受数据的时候使用List<Student>不就行了吗?需要那么纠结吗?
已经存在 2013-01-06
  • 打赏
  • 举报
回复
flexjson也不错
袭烽 2013-01-06
  • 打赏
  • 举报
回复
用谷歌的Gson工具可以更方便
失落夏天 2013-01-06
  • 打赏
  • 举报
回复
import org.codehaus.jackson.map.ObjectMapper; jar包:jackson-core-asl-1.8.1.jar
加载更多回复(4)

67,550

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧