复制代码

【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 需要传递三个参数 也很简单

posted @ 2018-12-16 14:30  pg633  阅读(258)  评论(0编辑  收藏  举报