Json与Bean的相互转换

ObjectMapper是jackson中的方法。

第一、将json字符串转为bean
public classStudentList { List student; public List getStudent() { returnstudent; } public void setStudent(List student) { this.student =student; } @Override public String toString() { return "StudentList[student=" + student + "]"; } }
public class JsonToJavaBean {
    public static void main(String[] args) {
        String str="{\"student\":[{\"name\":\"leilei\",\"age\":23},{\"name\":\"leilei02\",\"age\":23}]}";
        Student stu = null;
        List 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()+"   "+s.getAge());
        }
    }
}



第二、将bean转为json
public static void main(String[] args) {
        ArrayList list=new ArrayList();
        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 {
            objectMapper.writeValue(str, list);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
        System.out.println(str);
    }



本文是用CSDN中摘抄的。

你可能感兴趣的:(Json与Bean的相互转换)