joelittlejohn / jsonschema2pojo

Generate Java types from JSON or JSON Schema and annotate those types for data-binding with Jackson, Gson, etc
http://www.jsonschema2pojo.org
Apache License 2.0
6.23k stars 1.66k forks source link

Create complex types defined by default #689

Open ben-manes opened 7 years ago

ben-manes commented 7 years ago

This builds onto the discussion from #664. In this case I have a complex type to default, e.g.

"active": {
  "items": {
    "$ref": "#/definitions/edge"
  },
  "type": "array",
  "uniqueItems": true,
  "default": [
    { "entityId": "11111111-0000-0000-0000-000000000000", "displayName": "Entity" }
  ]
}

Ideally the generated type would have,

private Set<Edge> active = new LinkedHashSet<Edge>(Arrays.asList(new Edge(UUID.create("11111111-0000-0000-0000-000000000000"), "Entity");

but it generates,

private Set<Edge> active = new LinkedHashSet<Edge>(Arrays.asList(null));

Is it possible to generate complex types?

joelittlejohn commented 7 years ago

I think to support arbitrarily complex values for the default, we'd have to start using something like the Jackson ObjectMapper (or Gson, depending over what annotator is being used I guess). We could parse the value into a static field then reference this field as the default for instance fields.

joelittlejohn commented 7 years ago

I mean using the ObjectMapper in the generated source.

ben-manes commented 7 years ago

Yes, it might not be worthwhile especially if deserialization is required when creating a new instance. But perhaps then the observation here is that null is specified as an element in the collection. If js2p cannot create the value, I don't think null is a friendly alternative.

joelittlejohn commented 7 years ago

@ben-manes Yes, I guess we should remove the null here and simply ignore defaults that we can't map (for the time being).

giordanolucas commented 6 years ago

Is there any way to avoid initializing the collections with its default values? image Right now I'm getting this invalid code that I would like to avoid

joelittlejohn commented 6 years ago

There is no way to ignore the defaults I'm afraid, although I'd welcome a patch.