quicktype icon indicating copy to clipboard operation
quicktype copied to clipboard

Default property values for instantiation

Open schani opened this issue 7 years ago • 7 comments

From an Intercom user: They'd like quicktype to give default values to properties for the case of instantiating those classes, not for the case where the properties are missing when deserializing. In C#:

public string Kind {get; set; } = "music";

The simplest heuristic for that would be where we have more than N values and they're all the same.

schani avatar Feb 02 '18 03:02 schani

JSON Schema has a default keyword, but it applies to types, not to properties. It's probably good enough, though.

schani avatar Feb 11 '18 20:02 schani

Depends on #466

schani avatar May 01 '18 00:05 schani

I believe this issue is the same as:

https://github.com/quicktype/quicktype/issues/1415 https://github.com/quicktype/quicktype/issues/1535

I am on a project team that is also interested in the default use case.

colinsullivan avatar Nov 30 '21 03:11 colinsullivan

@schani My team also would like to have the default case for kotlin and swift. Any chance there is work being done to support this?

kathewang avatar Mar 30 '22 18:03 kathewang

@kathewang We accept PRs ;-)

schani avatar Mar 30 '22 19:03 schani

I implemented something like this in a project. Though it's not really generic at all. In our case one language is C++, and there we are using structs, and thus the "default value" concept is a bit different.

I wrote a subclass of the CppRenderer which constructs a std::map, then in our application code there is a factory pattern used to create objects and lookup default values in this auto-generated map.

colinsullivan avatar Mar 31 '22 01:03 colinsullivan

For TypeScript I used a similar factory pattern, but generated full method calls instead of a lookup table in a subclass of TypeScriptRenderer.

None of this is really generic. Thankfully the quicktype codebase is extensible in this way, or else we probably would have found another solution.

colinsullivan avatar Mar 31 '22 01:03 colinsullivan

Here's a patch for generating C++ default values that mostly works: https://gist.github.com/vnd/8e8b64268dca2bfe0f99a445bb0a7135

The only issue so far is with enums, which require trivial post-processing.

vnd avatar Mar 24 '23 07:03 vnd