1. 程式人生 > >【13】json-lib 使用轉換 jsonobj String

【13】json-lib 使用轉換 jsonobj String

先說一下,這裡有個問題 , 首先需要轉換的類一定要是public的,因為此處涉及到需要許可權訪問加共有構造

 

類程式碼

public class Student {
    //姓名
    private String name="";
    //年齡
    private String age="";
    //住址
    private String address="";
    public Student(){
        String name="";
        //年齡
        String age="";
        //住址
String address=""; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getAddress() {
return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + ", address=" + address + "]"; } }
View Code

使用程式碼

import
net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import java.sql.Struct; import java.util.ArrayList; import java.util.List; public class demo1 { public static void main(String []arg){ System.out.println("aaaaaaaaaa"); Student stu=new Student(); stu.setName("JSON"); stu.setAge("23"); stu.setAddress("北京市西城區"); // obj ->jsonobj JSONObject json = JSONObject.fromObject(stu); String str = json.toString(); System.out.println(str); //str -> jsonobj JSONObject json2 = JSONObject.fromObject(str); //jsonobj ->obj Student s = (Student)JSONObject.toBean(json2, Student.class); System.out.println(s); // list -> json List<Student> lists=new ArrayList<Student>(); lists.add(s); JSONArray json3= JSONArray.fromObject(lists); System.out.println(json3.toString()); List<Student> list = (List<Student>) JSONArray.toList(JSONArray.fromObject(json3.toString()) , Student.class); for(Student st :list){ System.out.println(st); } } }
View Code

這裡還有一個主義的 轉換物件toBean ,map 需要傳遞三個引數 也很簡單