Gson解析Date格式

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        List<User> list = new ArrayList<User>();
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        User u = new User();
        u.name = "111";
        u.date = new Date();
        list.add(u);
        User u1 = new User();
        u1.name = "222";
        u1.date = new Date();
        list.add(u1);
        User u2 = new User();
        u2.name = "333";
        u2.date = new Date();
        list.add(u2);
        ((TextView)findViewById(R.id.tv)).setText(gson.toJson(list));


    }

    class User{
        public String name;
        public Date date;
    }
}

运行结果如下所示:

相当于

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        List<User> list = new ArrayList<User>();
// Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        Gson gson = new Gson();
        User u = new User();
        u.name = "111";
        u.date = new Date();
        list.add(u);
        User u1 = new User();
        u1.name = "222";
        u1.date = new Date();
        list.add(u1);
        User u2 = new User();
        u2.name = "333";
        u2.date = new Date();
        list.add(u2);
// ((TextView)findViewById(R.id.tv)).setText(gson.toJson(list));

        /** * TypeToken的使用非常简单,只要将需要获取类型的泛型类作为TypeToken * 的泛型参数构造一个匿名的子类,就可以通过getType()方法获取到我们使 * 用的泛型类的泛型参数类型。 */
        Type listType = new TypeToken<List<User>>(){}.getType();
        List<User> users = gson.fromJson(gson.toJson(list),listType);
        for(User m : users){
            Log.e("users:",new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(m.date));
            Log.e("users:",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(m.date));

        }


    }

    class User{
        public String name;
        public Date date;
    }
}

通过SimpleDateFormat来设定json输出的date的格式,输出结果如下所示:
Gson解析Date格式_第1张图片

你可能感兴趣的:(Gson解析Date格式)