把json格式转换成javaBean才可以。
于是查了一下资料,网上最多的资料就是下面的这种方式:
1
2
3
4
5
6
7
8
9
|
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
继续网上搜了一下这个类用法的例子,有,但是比较少,没有直接可以现成用的。
于是就开始自己尝试各种方法来做例子。
首先字符串:
1
|
String str= "{"student":[{"name":"leilei","age":23},{"name":"leilei02","age":23}]}" ; |
接下来创建的是StudentList类
1
2
3
4
5
6
7
8
9
10
|
public class StudentList { List<Student> student; public List<Student> getStudent() { return student; } public void setStudent(List<Student> student) { this .student = student; } } |
下面是Student类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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; } } |
最后测试程序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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;
}