如何创建String Format模板以生成Eclipse自动生成toString的Json

时间:2017-01-31 21:16:00

标签: java arrays json eclipse

Eclipse提供了为每个类自动生成toString方法的选项。

进一步利用这个功能,我正在创建字符串格式模板,以便在eclipse生成toString方法时以Json格式提供。

我使用了以下字符串格式模板:

 { ${member.name()}:"${member.value}", ${otherMembers}}

现在我生成了toString方法,如下面的POJO但是当我运行这个程序时,我得到的结果是,而不是有效的JSON。

{ name:"null", reportees:"[1, 2, 3]", department:"[retail, banking, finance]", owns:"null", supplimentary:"null}

代码

public class TestPojo {
  private String name;
  private List<String> reportees;
  private String[] department;
  private Machine owns;
  private List<Machine> supplimentary;

public static void main(String arg[]) {
    TestPojo aTestPojo = new TestPojo();
    aTestPojo.department = new String[] { "retail", "banking", "finance" };
    aTestPojo.reportees = new ArrayList<String>() {

        {
            add("1");
            add("2");
            add("3");
        }
    };
    System.out.print(aTestPojo);
}

public static class Machine {

    private String machineName;
    private String duties;

    public String getMachineName() {
        return machineName;
    }

    public void setMachineName(String machineName) {
        this.machineName = machineName;
    }

    public String getDuties() {
        return duties;
    }

    public void setDuties(String duties) {
        this.duties = duties;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("{ machineName:\"").append(machineName).append("\", duties:\"").append(duties).append("}");
        return builder.toString();
    }

}

@Override
public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("{ name:\"").append(name).append("\", reportees:\"").append(reportees).append("\", department:\"").append(Arrays.toString(department)).append("\", owns:\"").append(owns).append("\", supplimentary:\"").append(supplimentary).append("}");
    return builder.toString();
}

}

3 个答案:

答案 0 :(得分:3)

Lifecycle of a fragment想法的帮助下。我构建了一个&#34; Eclipse Custom toString()构建器&#34;生成toString方法代码以返回当前对象的JSON格式字符串。

关注此解决方案的github单击[Eclipse toString_Builder for JSON](@dvlcube,&#34; Custom Eclipse toString()Builder&#34;)

样本测试代码

{"name": null,"reportees": ["1","2","3"],"department": ["retail","banking","finance"],"owns": null,"supplimentary": [{"machineName": "Train","duties": "travel"},{"machineName": "Lorry","duties": "Carrier"}],"i": 10,"machineList": {"Lorry": {"machineName": "Lorry","duties": "Carrier"},"Train": {"machineName": "Train","duties": "travel"}}}

在运行此程序时,我得到了以下JSON输出

{{1}}

答案 1 :(得分:2)

由于打印数组和集合的方式,它不是有效的JSON(&#34; [1,2,3]&#34;而不是[&#34; 1&#34;,& #34; 2&#34;&#34; 3&#34;。])

此外,它不会通过严格的JSON验证,因为字段名称也应该被引用。

Eclipse的字符串格式模板非常有用,但为了完全控制,最好创建一个构建器类。

这里a gist就是这样做的。您可以展开它,它适用于您的示例类开箱即用。

您可以使用此类在Eclipse中生成toString()方法。

答案 2 :(得分:0)

仅推荐用于字符串值。下面的表达式为您提供 JSON toString 生成。

{"${member.name()}":"${member.value}", "${otherMembers}"}