我的项目中有一个 Java 类 User,它有 2 个属性 id
和 created
。
用户.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/