JSON的转换

1、在html页面中json的转换




    
    Title




2、在java中json的转换 

需要引入这个jar包 

 


public class User {
    private String id;
    private String username;

    public User(String id, String username) {
        this.id = id;
        this.username = username;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", username='" + username + '\'' +
                '}';
    }
}
public class Test {
    public static void main(String[] args) {
        //将对象转换成json格式的字符串
        User user = new User("1", "张三");
        Gson gson = new Gson();
        String s = gson.toJson(user);
        System.out.println("将对象转换成json格式的字符串\t\t"+s);

        //将json格式的字符串转对象,底层是通过反射来完成的
        User user1 = gson.fromJson(s, User.class);
        System.out.println(user1);

        //将List集合转换成json格式的字符串
        ArrayList list = new ArrayList<>();
        list.add(new User("1","张三"));
        list.add(new User("2","李四"));
        list.add(new User("3","王五"));
        String s1 = gson.toJson(list);
        System.out.println(s1);
        //将list类型的json格式的字符串转成对象
        Type type = new TypeToken>() {
        }.getType();
        Object o = gson.fromJson(s1, type);
        System.out.println(o);

        //将map集合转成json格式的字符串
        HashMap hashMap = new HashMap<>();
        hashMap.put("a","张三");
        hashMap.put("b","李四");
        hashMap.put("c","王五");
        String s2 = gson.toJson(hashMap);
        System.out.println(s2);
        //将map类型的json格式的字符串转成对象
        Type type1 = new TypeToken>() {
        }.getType();
        Object o1 = gson.fromJson(s2, type1);
        System.out.println(o1);


    }
}

你可能感兴趣的:(servlet,json)