Java学习之对象和Json的相互转化

JacksonJson是SpringMVC内置的json处理工具,其中有一个ObjectMapper类,可以方便的实现对json的处理:

ObjectMapper mapper = new ObjectMapper();

对象user:

public class user {
    private String userName;
    private String userid;
    private int age;

    public user() {
    }

    public user(String userName, String userid, int age) {
        this.userName = userName;
        this.userid = userid;
        this.age = age;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setUserid(String userid) {
        this.userid = userid;
    }

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

    public String getUserName() {
        return userName;
    }

    public String getUserid() {
        return userid;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "user{" +
                "userName='" + userName + '\'' +
                ", userid='" + userid + '\'' +
                ", age=" + age +
                '}';
    }
}
View Code

测试:

public class Test {
    public static void main(String[] args) throws IOException {
        user user = new user();
        user.setAge(22);
        user.setUserName("张三");
        user.setUserid("007");
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(user);
        System.out.println(json);
        user user1 = mapper.readValue(json, user.class);
        System.out.println(user1);
    }
}

结果:

{"userName":"张三","userid":"007","age":22}(json格式)
user{userName='张三', userid='007', age=22}(对象的toString)

 

posted @ 2021-01-27 20:30  请别耽误我写BUG  阅读(76)  评论(0编辑  收藏  举报