1. 程式人生 > >json字串和bean轉換

json字串和bean轉換

在開發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@3ca83695
leilei   23
leilei02   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