java - 如何让 Timestamp 对象在 JSON 中以 long 类型显示?

标签 java json

我的项目中有一个 Java 类 User,它有 2 个属性 idcreated

用户.java

import java.sql.Timestamp;

public class User {

    private int id;
    private Timestamp created;

    public User (int id) {
        this.id = id;
        created = new Timestamp(System.currentTimeMillis());
    }
    // getters and setters...
}

现在我需要生成一个表示 User 实例的 JSON 对象。所以我使用 org.json.JSONObject 来做到这一点:

User user = new User(1);
JSONObject json = new JSONObject(user);
System.out.println(json.toString());

这是结果。

{"id":1,"created":"2016-03-02 19:08:00.0"}

但是,我想要一个 Long 格式,就像

{"id":1,"created":1456945720000}

我想我也许可以通过修改 JSONObject 中的属性来更改它,但我想知道是否有更好的方法。

最佳答案

使用.getTime()转换为long。
如果您在变量“created”中获取一个对象,则将其转换为 long :

created.getTime();

关于java - 如何让 Timestamp 对象在 JSON 中以 long 类型显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35756127/

相关文章:

java - Eclipse WTP安装失败 "Cannot complete the install because one or more required items could not be found"

java - NullPointerException:没有给出应用程序实例,getinstance() 甚至 this(!?) 似乎返回 null

java - 无法从类外部访问方法

json - 在 Monaco Editor 中点击按钮折叠展开

ios - 如何在 swift 中为 Post 请求创建 JSON Body

javascript - 如何创建具有空值的对象?

java - FileWriter,如何在同一个文件上写

java - eclipse中的maven在哪里?

php ini 与 json 并停止编译器 hack

java - Jackson OffsetDateTime 序列化 Z 而不是 +00 :00 timezone?