Java 中的 toString 方法产生的输出不能满足我的需求。我正在寻找一种方法来启用 toString 方法输出 json 字符串。而且,因为这个功能会被频繁使用,所以最好统一配置。可以使用统一的配置点让toString输出json。最坏的情况下,他也应该通过给每个类添加注解的方式来实现。 我之前把希望寄托在lombok库上,然而lombok社区明确拒绝实现这个功能。杰克逊似乎也没有这个特点。还有其他方法可以达到这个要求吗?
public class User {
private String userId;
private String uswrName;
// I don't want to write any toString method
//public String toString () {}
}
User user = new User();
user.setUserName("xxxxxxx");
// I want him to output a JSON string
System.out.print(user);
如果您不想在
User类中使用
toString()
方法,那么就不要使用它。按照@Ti7的建议,向您的 User类添加
toJSON()
方法,例如,在您的 User 类中使用 Jackson API (com.fasterxml.jackson):
public class User {
private String userId;
private String userName;
public User() { }
public User(String userId, String userName) {
this.userId = userId;
this.userName = userName;
}
public String getUserID() {
return this.userId;
}
public void setUserID(String userId) {
this.userId = userId;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
/**
* Converts this instance of User to a JSON string in either Compact-Print
* or in default Pretty-Print.<br>
*
* @param asCompactPrint (boolean - varArg - Optional) By default Compact-
* Print is false which tells the method to create the JSON string in a
* Pretty-Print format. If boolean <b>true</b> is supplied then a Compact-
* Print format JSON string is returned.<br>
*
* @return (String) The current Object instance converted to a JSON String.
*/
/**
* Converts this instance of User to a JSON string in either Compact-Print
* or in default Pretty-Print.<br>
*
* @param asCompactPrint (boolean - varArg - Optional) By default Compact-
* Print is false which tells the method to create the JSON string in a
* Pretty-Print format. If boolean <b>true</b> is supplied then a Compact-
* Print format JSON string is returned.
*
* @return (String) The current Object instance converted to a JSON String.
*/
public String toJSON (boolean... asCompactPrint) {
boolean compact = false;
if (asCompactPrint.length > 0) {
compact = asCompactPrint[0];
}
String resultString = null;
try {
com.fasterxml.jackson.databind.ObjectMapper mapper
= new com.fasterxml.jackson.databind.ObjectMapper();
if (compact) {
// Java object to Compact-Print JSON string:
resultString = mapper.writeValueAsString(this);
}
else {
// Java object to Pretty-Print JSON string:
resultString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this);
}
}
catch (com.fasterxml.jackson.core.JsonProcessingException ex) {
System.err.println(ex);
}
return resultString;
}
}
使用示例:
User user = new User("A0001", "Fred FlintStone");
System.out.println(user.toJSON());
控制台输出:
{
"userName" : "Fred FlintStone",
"userID" : "A0001"
}