將對象轉換成Json數據


解析Json數據是:Json->對象封裝

那么從對象->Json數據的方式如下:

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

class Student {
    private int age;
    private String name;

    public Student(int age, String name) {
        super();
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

}

public class Test {
    public static void main(String[] args) {
        // java Bean--->json數據
        Student student = new Student(19, "鳳姐");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("name", student.getName());
            jsonObject.put("age", student.getAge());

            String json = jsonObject.toString();
            System.out.println(json);
            List<Student> list = new ArrayList<>();
            // 集合---》JSONArray
            list.add(student);
            list.add(new Student(18, "芙蓉姐姐"));
            list.add(new Student(28, "犀利哥"));
            JSONArray jsonArray = new JSONArray();
            for (Student student2 : list) {
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("age", student2.getAge());
                jsonObject2.put("name", student2.getName());
                jsonArray.put(jsonObject2);
            }

            System.out.println(jsonArray.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

}

 


免責聲明!

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



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