joelittlejohn/jsonschema2pojo — pull request #204 by jburnim (2014-06-12 20:34:26+00:00)
Title: Adds options to generate immutable types.

The purpose of this PR is to add options for generating immutable Java types. Please let me know if you think something like this would be useful to add to jsonschem2pojo. (We're using these modifications internally at Sift Science.)

For the address.json example, the generated code with `immutable=true` and `generateBuilderClasses=true` looks roughly like:
```java
@JsonDeserialize(builder = Address.Builder.class)
public class Address {
@JsonProperty("post-office-box")
private final String postOfficeBox;
...
@JsonIgnore
private final Map additionalProperties;

private Address(Address.Builder builder) {
this.postOfficeBox = builder.postOfficeBox;
...
this.additionalProperties = ImmutableMap.copyOf(builder.additionalProperties);
}

// no setter methods

public static Address.Builder newBuilder() {
return new Address.Builder();
}

@JsonProperty("post-office-box")
public String getPostOfficeBox() {
return postOfficeBox;
}
...
@JsonAnyGetter
public Map getAdditionalProperties() {
return this.additionalProperties;
}

public final static class Builder {
private String postOfficeBox;
...
private Map additionalProperties = new HashMap();

private Builder() { }

public Address build() {
return new Address(this);
}

@JsonProperty("post-office-box")
public Address.Builder withPostOfficeBox(String postOfficeBox) {
this.postOfficeBox = postOfficeBox;
return this;
}

public Address.Builder withAdditionalProperties(Map additionalProperties) {
this.additionalProperties = additionalProperties;
return this;
}

@JsonAnySetter
public Address.Builder withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
}
}
```

And generated code with `immutable=true`, `generateBuilderClasses=true`, and `usePublicFields=true` looks roughly like:
```java
@JsonDeserialize(builder = Address.Builder.class)
public class Address {
@JsonProperty("post-office-box")
public final String postOfficeBox;
...
@JsonIgnore
public final Map additionalProperties;

private Address(Address.Builder builder) {
this.postOfficeBox = builder.postOfficeBox;
...
this.additionalProperties = ImmutableMap.copyOf(builder.additionalProperties);
}

// no setter or getter methods

public static Address.Builder newBuilder() {
return new Address.Builder();
}

public final static class Builder {
// Builder is identical to above
...
}
}
```

At the moment, the options `immutable=true` and `generateBuilderClasses=false` don't work together. (For these options, it is necessary to generate a constructor that takes one argument per property and initializes all property fields, but I haven't written code to do this.) I can merge these options into one or maybe take a stab at generating constructors for immutable Java types.