Gson解析Json格式数据

时间:2021-07-03 20:00:05
//数据定义:===========================================
    class User{
        String name; String password;
        String getName(){}
        void setName(){}
    }
    Gson gson=new Gson();
//===================

//解析一条json数据:令str为[{"name":"21001","password":"21001"}] =======
    User user=new User();
    user=gson.fromJson(str,User.class);
//===================

//解析多条json数据=====================================
//令str为[{"name":"21001","password":"21001"},{"name":"21001","password":"21001"},{"name":"21001","password":"21001"}]
    List<User> user_list;
    user_list=gson.fromJson(str, new TypeToken<List<User>>(){}.getType());
//===================

//打包一条json数据=========
    User user=new User();
    初始化user
    str=gson.toJson(user);
//===================

//打包多条json数据=========
    List<User> user_list
    初始化user_list
    str=gson.toJson(use_list);
//====================