将对象转换成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();
        }

    }

}

 

posted @ 2016-07-20 16:48  ts-android  阅读(3142)  评论(2编辑  收藏  举报