使用 Gson 序列化 和 反序列化 json

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class Main {

    public static void main(String[] args) {

        User user = new User();
        user.setId(1);
        user.setUser("admin");

        # 实例化 Gson
        Gson gson = new Gson();
        # 序列化 json
        String jsonUser = gson.toJson(user);
        System.out.println(jsonUser);
        # 反序列化 json
        User user1 = gson.fromJson(jsonUser, User.class);
        System.out.println(user1);

        System.out.println("==============================");

        # 列表,使用 List
        List<User> users = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
        users.add(user);
        }
        String jsonUsers = gson.toJson(users);
        System.out.println(jsonUsers);

        List<User> users1 = gson.fromJson(jsonUsers, new TypeToken<List<User>>() {
        }.getType());
        for (User _user : users1) {
        System.out.println(_user);
        }

        System.out.println("==============================");

        # 多属性键值对,使用 Map
        Map<String, String> ips = new HashMap<>();
        for (int i = 0; i < 9; i++) {
            ips.put(i + "", "192.168.1.10" + i);
        }
        String jsonIps = gson.toJson(ips);
        System.out.println(jsonIps);

        Map<String, String> ips1 = gson.fromJson(jsonIps, new TypeToken<Map<String, String>>() {
        }.getType());
        Set<String> set = ips1.keySet();
        for (String _string : set) {
        System.out.println(_string + ":" + ips1.get(_string));
        }
    }
}

# 用到的类
public class User {

    private int id;
    private String user;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", user='" + user + '\'' +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注

2 × 4 =