Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create String Format template to generate Json for Eclipse autogenerated toString

Eclipse gave option to auto generate the toString method for every class.

Further leverage this facility, I am creating String Format Template to give as Json format when eclipse generate toString Method.

I used following String Format Template:

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

now i generated toString method as following POJO but When i run this program i got result as and not a VALID JSON.

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

Code

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

}

like image 863
Dhana Avatar asked Jan 31 '17 21:01

Dhana


2 Answers

With the help of @dvlcube idea. I built a "Eclipse Custom toString() builder" to generate toString method code to return a JSON formatted string of current object.

Follow the github for this solution Click [Eclipse toString_Builder for JSON](https://github.com/djaganathan/EclipseToStringBuilderForJson/blob/master/src/main/java/com/github/djaganathan/opensource/eclipse/util/JsonToStringBuilder.java,"Custom Eclipse toString() Builder")

Sample Testing Code

import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.time.StopWatch;
import org.elasticsearch.common.collect.Lists;

public class TestPojo {

    private String name;
    private List<String> reportees;
    private String[] department;
    private Machine owns;
    private List<Machine> supplimentary;
    private int i = 10;
    private Map<String, Machine> machineList = Maps.newConcurrentMap();

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

        Machine aMachine = new Machine("Train", "travel");
        Machine aMachine1 = new Machine("Lorry", "Carrier");
        aTestPojo.supplimentary = Lists.newArrayList(aMachine, aMachine1);
        aTestPojo.machineList.put("Train", aMachine);
        aTestPojo.machineList.put("Lorry", aMachine1);

        System.out.print(aTestPojo);
    }

    public static class Machine {
          private String machineName;
          private String duties;

        public Machine(String machineName, String duties) {
            super();
            this.machineName = machineName;
            this.duties = 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() {
        JsonToStringBuilder builder = new JsonToStringBuilder(this);
        builder.append("machineName", machineName);
        builder.append("duties", duties);
        return builder.build();
    }
}

@Override
public String toString() {
    JsonToStringBuilder builder = new JsonToStringBuilder(this);
    builder.append("name", name);
    builder.append("reportees", reportees);
    builder.append("department", department);
    builder.append("owns", owns);
    builder.append("supplimentary", supplimentary);
    builder.append("i", i);
    builder.append("machineList", machineList);
    String value = builder.build();
    return value;
    }
}

While running this program i got the following JSON output

{"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"}}}
like image 189
Dhana Avatar answered Oct 21 '22 08:10

Dhana


It's not valid JSON because of the way arrays and collections are being printed ("[1,2,3]" instead of ["1","2","3"]).

Also, it wouldn't pass strict JSON validation because the field names should be quoted as well.

Eclipse's String Format Template can be very useful, but for full control it's better to create a builder class.

Here's a gist for doing just that. You can expand on it, and it works for your example class out of the box.

You can use this class to generate the toString() methods in Eclipse.

like image 40
dvlcube Avatar answered Oct 21 '22 09:10

dvlcube