json

json这么常用你说不会不好吧

先导入jar包

json_第1张图片

准备一个User实体类

package com.test;

public class User {
    private String name;
    private String gender;

    public User() {
    }

    public User(String name, String gender) {
        this.name = name;
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

}

把一个对象转换成json

@Test
    public void testUserObject() {
        User u = new User();
        u.setGender("男");
        u.setName("dust");
        JSONObject jsonObject = JSONObject.fromObject(u);
        System.out.println(jsonObject.toString());


    }
{"gender":"男","name":"dust"}

把数组,集合转换成json格式

// 数组,集合
    @Test
    public void tsetUserArray() {
        List<User> userList = new ArrayList<User>();
        userList.add(new User("男", "张三"));
        userList.add(new User("男", "李四"));
        userList.add(new User("男", "王武"));
        userList.add(new User("女", "dust"));
        JSONArray jsonArray = JSONArray.fromObject(userList);
        String json = jsonArray.toString();
        System.out.println(json);
    }
[{"gender":"张三","name":"男"},{"gender":"李四","name":"男"},{"gender":"王武","name":"男"},{"gender":"dust","name":"女"}]

json过滤属性

// 过滤
    @Test
    public void testJsonConfig() {
        User u = new User();
        u.setGender("男");
        u.setName("小李");
        //过滤
        JsonConfig jsonConfig = new JsonConfig();
        //可以过滤多个属性
        jsonConfig.setExcludes(new String[] { "gender" });
        JSONObject jsonObject = JSONObject.fromObject(u, jsonConfig);
        System.out.println(jsonObject.toString());
    }
{"name":"小李"}

你可能感兴趣的:(json)