json字符串和bean转换

来源:互联网 发布:linux查看所有文件夹 编辑:程序博客网 时间:2024/05/16 04:13

在开发javaweb的时候经常会使用json的数据格式在前后台进行数据交互,刚接触json就写个博客记录自己对json数据转换的简单理解,废话不说,下面开始。

StudentList的定义如下:

public class StudentList {    private List<Student> student;    public List<Student> getStudent() {        return student;    }    public void setStudent(List<Student> student) {        this.student = student;    }    public StudentList() {        super();    }    public StudentList(List<Student> student) {        super();        this.student = student;    }}

下面代码是一个测试类:

public class JsonTest {        //json字符串        String str = "{\"student\":[{\"name\":\"leilei\",\"age\":23},{\"name\":\"leilei02\",\"age\":23}]}";        String str1 = "{\"student1\":[{\"name\":\"leilei\",\"age\":23},{\"name\":\"leilei02\",\"age\":23}]}";        System.out.println(str1);        Student stu = null;        List<Student> list = null;        try {            ObjectMapper objectMapper = new ObjectMapper();            //将json字符串解析成实体类,第一个参数str1表示要转化的json串,第二个参数转成的实体类Class            StudentList studentList = objectMapper.readValue(str1,StudentList.class);            System.out.println(studentList);            list = studentList.getStudent();        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        for (Student s : list) {            System.out.println(s.getName() + "   " + s.getAge());        }    }}

可以看到我在StudentList类中定义student对象,这个对象名称在json转化成javabean的时候很关键。ObjectMapper的readValue(str1,StudentList)方法,作用是将一个json字符串转化成javabean,应用的是反射机制,首先要查找StudentList这个类是否有存在json串中的student1这个变量,如果没有会报下面的错误:
Unrecognized field “student1” (Class test.StudentList), not marked as ignorable

大概意思就是说字符串json中这个student1在StudentList这个类中找不到对应的属性和它匹配。再来看看str1是什么?
“{\”student1\”:[{\”name\”:\”leilei\”,\”age\”:23},{\”name\”:\”leilei02\”,\”age\”:23}]}” 这个json串中student1就是为了匹配StudentList的student属性,因此名称要一致。找到之后,创建有参的构造函数,然后将Student的属性赋值。

正确的应该是:
json串:
“{\”student\”:[{\”name\”:\”leilei\”,\”age\”:23},{\”name\”:\”leilei02\”,\”age\”:23}]}”
转换的实体类:

public class StudentList {    //属性定义要和json中的一致    private List<Student> student;    public List<Student> getStudent() {        return student;    }    public void setStudent(List<Student> student) {        this.student = student;    }    public StudentList() {        super();    }    //有参的构造函数    public StudentList(List<Student> student) {        super();        this.student = student;    }}

打印结果:

{"student1":[{"name":"leilei","age":23},{"name":"leilei02","age":23}]}test.StudentList@3ca83695leilei   23leilei02   23

javabean怎样转化成json?

下面是测试代码:

public class BeanToJson {    public static void main(String[] args) {        ArrayList<Student> list=new ArrayList<Student>();        Student s1=new Student();        s1.setName("leilei");        s1.setAge(23);        Student s2=new Student();        s2.setName("leilei02");        s2.setAge(23);        list.add(s1);        list.add(s2);        StringWriter str=new StringWriter();        ObjectMapper objectMapper=new ObjectMapper();        try {            //将list集合中的实体存储在字符串中            objectMapper.writeValue(str, list);        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }           System.out.println(str);    }}

还是用了ObjectMapper这个类,这次调用的是writeValue(str,list)方法,第一个参数是被转化的json串接收对象,第二个参数是被转化的对象。要注意str的类型是StringWriter而不是String,StringWriter内部还是用的StringBuffer,主要是为了方便对字符串的操作。

public class StringWriter extends Writer {    private StringBuffer buf;    /**     * Create a new string writer using the default initial string-buffer     * size.     */    public StringWriter() {        buf = new StringBuffer();        lock = buf;    }

运行结果:

[{"name":"leilei","age":23,"sex":"\u0000"},{"name":"leilei02","age":23,"sex":"\u0000"}]

因为我后来给Student添加了一个字段,而字符串json中没有对应的键值对,打印的时候出现”\u0000”代表null

0 0
原创粉丝点击