Java實現JSONObject對象與Json字符串互相轉換


Java實現JSONObject對象與Json字符串互相轉換

JSONObject 轉 JSON 字符串

Java代碼:

		JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "wjw");
        jsonObject.put("age", 22);
        jsonObject.put("sex", "男");
        jsonObject.put("school", "商職");
        String jsonStr = JSONObject.toJSONString(jsonObject);
        System.out.println(jsonStr);

執行結果:

{"school":"商職","sex":"男","name":"wjw","age":22}

JSON 字符串 轉 JSONObject 對象

Java代碼:

        String jsonStr = "{\"school\":\"商職\",\"sex\":\"男\",\"name\":\"wjw\",\"age\":22}";
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        System.out.println(jsonObject.getString("name"));
        System.out.println(jsonObject.getInteger("age"));

執行結果:

wjw
22

實體類 轉 JSONObject對象

創建Person類:

package c;

public class Person {

    private String name; // 姓名

    private int age;  // 年齡

    private String sex;  // 性別

    private String school;  // 學校

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getSchool() {
        return school;
    }

    public void setSchool(String school) {
        this.school = school;
    }
}

創建 Person 對象:

        Person person = new Person();
        person.setName("wjw");
        person.setAge(22);
        person.setSex("男");
        person.setSchool("商職");
        String personStr = JSONObject.toJSONString(person);  // 轉換為json字符串
        System.out.println("personStr:"+personStr);
        JSONObject personObject = JSONObject.parseObject(personStr);  // 轉換為json對象
        System.out.println("personObject:"+personObject);
        System.out.println("name:"+personObject.getString("name"));

打印結果:

personStr:{"age":22,"name":"wjw","school":"商職","sex":"男"}
personObject:{"school":"商職","sex":"男","name":"wjw","age":22}
name:wjw


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM