如何使toString方法自动输出JSON字符串,而无需手动连接JSON字符串?

mzsu5hc0  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(68)

Java中的toString方法产生的输出并不能满足我的需求,我正在寻找一种方法能够让toString方法输出json字符串,而且因为这个函数会被非常频繁的使用,所以最好统一配置,可以使用统一的配置点让toString输出json,最坏的情况下他还应该通过为每个类添加注解来实现它。我以前把希望寄托在lombok库上,然而,Lombok岛社区显然拒绝实现这个功能。2Jackson似乎也没有这个功能。3有没有其他方法来实现这个功能要求?

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);

字符串

w1e3prcc

w1e3prcc1#

如果你不想在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"
}

相关问题