Generated-output differences

quicktype output changed between the PR base and tested PR merge revisions.
← Back to the pull request
1test cases
31files differ
0modified
31new
0deleted
2,470changed lines
+2,470 −0insertions / deletions
Base a49b94e8f6f1b319a4da9fb15d57ef13ba316ddc · PR merge 03fa4971d33cfebfeb628b6bdae4c53349bccf6d · Head 2dcbd3abe5038446a3f5952c8fb5e3c87a364ca2 · raw patch
Test case

test/inputs/schema/allof-closed-objects.schema

31 generated files · +2,470 −0
Aschema-cplusplusdefault / quicktype.hpp+155 −0
@@ -0,0 +1,155 @@
1+// To parse this JSON data, first install
2+//
3+// json.hpp https://github.com/nlohmann/json
4+//
5+// Then include this file, and then do
6+//
7+// TopLevel data = nlohmann::json::parse(jsonString);
8+
9+#pragma once
10+
11+#include <optional>
12+#include "json.hpp"
13+
14+#include <optional>
15+#include <stdexcept>
16+#include <regex>
17+
18+#ifndef NLOHMANN_OPT_HELPER
19+#define NLOHMANN_OPT_HELPER
20+namespace nlohmann {
21+ template <typename T>
22+ struct adl_serializer<std::shared_ptr<T>> {
23+ static void to_json(json & j, const std::shared_ptr<T> & opt) {
24+ if (!opt) j = nullptr; else j = *opt;
25+ }
26+
27+ static std::shared_ptr<T> from_json(const json & j) {
28+ if (j.is_null()) return std::shared_ptr<T>(); else return std::make_shared<T>(j.get<T>());
29+ }
30+ };
31+ template <typename T>
32+ struct adl_serializer<std::optional<T>> {
33+ static void to_json(json & j, const std::optional<T> & opt) {
34+ if (!opt) j = nullptr; else j = *opt;
35+ }
36+
37+ static std::optional<T> from_json(const json & j) {
38+ if (j.is_null()) return std::optional<T>(); else return std::make_optional<T>(j.get<T>());
39+ }
40+ };
41+}
42+#endif
43+
44+namespace quicktype {
45+ using nlohmann::json;
46+
47+ #ifndef NLOHMANN_UNTYPED_quicktype_HELPER
48+ #define NLOHMANN_UNTYPED_quicktype_HELPER
49+ inline json get_untyped(const json & j, const char * property) {
50+ if (j.find(property) != j.end()) {
51+ return j.at(property).get<json>();
52+ }
53+ return json();
54+ }
55+
56+ inline json get_untyped(const json & j, std::string property) {
57+ return get_untyped(j, property.data());
58+ }
59+ #endif
60+
61+ #ifndef NLOHMANN_OPTIONAL_quicktype_HELPER
62+ #define NLOHMANN_OPTIONAL_quicktype_HELPER
63+ template <typename T>
64+ inline std::shared_ptr<T> get_heap_optional(const json & j, const char * property) {
65+ auto it = j.find(property);
66+ if (it != j.end() && !it->is_null()) {
67+ return j.at(property).get<std::shared_ptr<T>>();
68+ }
69+ return std::shared_ptr<T>();
70+ }
71+
72+ template <typename T>
73+ inline std::shared_ptr<T> get_heap_optional(const json & j, std::string property) {
74+ return get_heap_optional<T>(j, property.data());
75+ }
76+ template <typename T>
77+ inline std::optional<T> get_stack_optional(const json & j, const char * property) {
78+ auto it = j.find(property);
79+ if (it != j.end() && !it->is_null()) {
80+ return j.at(property).get<std::optional<T>>();
81+ }
82+ return std::optional<T>();
83+ }
84+
85+ template <typename T>
86+ inline std::optional<T> get_stack_optional(const json & j, std::string property) {
87+ return get_stack_optional<T>(j, property.data());
88+ }
89+ #endif
90+
91+ class Dog {
92+ public:
93+ Dog() = default;
94+ virtual ~Dog() = default;
95+
96+ private:
97+ std::string discriminator;
98+ std::optional<std::string> foo;
99+ std::optional<std::string> bar;
100+
101+ public:
102+ const std::string & get_discriminator() const { return discriminator; }
103+ std::string & get_mutable_discriminator() { return discriminator; }
104+ void set_discriminator(const std::string & value) { this->discriminator = value; }
105+
106+ std::optional<std::string> get_foo() const { return foo; }
107+ void set_foo(std::optional<std::string> value) { this->foo = value; }
108+
109+ std::optional<std::string> get_bar() const { return bar; }
110+ void set_bar(std::optional<std::string> value) { this->bar = value; }
111+ };
112+
113+ class TopLevel {
114+ public:
115+ TopLevel() = default;
116+ virtual ~TopLevel() = default;
117+
118+ private:
119+ std::optional<Dog> animal;
120+
121+ public:
122+ std::optional<Dog> get_animal() const { return animal; }
123+ void set_animal(std::optional<Dog> value) { this->animal = value; }
124+ };
125+}
126+
127+namespace quicktype {
128+ void from_json(const json & j, Dog & x);
129+ void to_json(json & j, const Dog & x);
130+
131+ void from_json(const json & j, TopLevel & x);
132+ void to_json(json & j, const TopLevel & x);
133+
134+ inline void from_json(const json & j, Dog& x) {
135+ x.set_discriminator(j.at("discriminator").get<std::string>());
136+ x.set_foo(get_stack_optional<std::string>(j, "foo"));
137+ x.set_bar(get_stack_optional<std::string>(j, "bar"));
138+ }
139+
140+ inline void to_json(json & j, const Dog & x) {
141+ j = json::object();
142+ j["discriminator"] = x.get_discriminator();
143+ j["foo"] = x.get_foo();
144+ j["bar"] = x.get_bar();
145+ }
146+
147+ inline void from_json(const json & j, TopLevel& x) {
148+ x.set_animal(get_stack_optional<Dog>(j, "animal"));
149+ }
150+
151+ inline void to_json(json & j, const TopLevel & x) {
152+ j = json::object();
153+ j["animal"] = x.get_animal();
154+ }
155+}
Aschema-csharp-recordsdefault / QuickType.cs+73 −0
@@ -0,0 +1,73 @@
1+// <auto-generated />
2+//
3+// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
4+//
5+// using QuickType;
6+//
7+// var topLevel = TopLevel.FromJson(jsonString);
8+#nullable enable
9+#pragma warning disable CS8618
10+#pragma warning disable CS8601
11+#pragma warning disable CS8602
12+#pragma warning disable CS8603
13+#pragma warning disable CS8604
14+#pragma warning disable CS8625
15+#pragma warning disable CS8765
16+
17+namespace QuickType
18+{
19+ using System;
20+ using System.Collections.Generic;
21+
22+ using System.Globalization;
23+ using Newtonsoft.Json;
24+ using Newtonsoft.Json.Converters;
25+
26+ public partial record TopLevel
27+ {
28+ [JsonProperty("animal")]
29+ public Dog? Animal { get; set; }
30+ }
31+
32+ public partial record Dog
33+ {
34+ [JsonProperty("discriminator", Required = Required.Always)]
35+ public string Discriminator { get; set; }
36+
37+ [JsonProperty("foo")]
38+ public string? Foo { get; set; }
39+
40+ [JsonProperty("bar")]
41+ public string? Bar { get; set; }
42+ }
43+
44+ public partial record TopLevel
45+ {
46+ public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings);
47+ }
48+
49+ public static partial class Serialize
50+ {
51+ public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
52+ }
53+
54+ internal static partial class Converter
55+ {
56+ public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
57+ {
58+ MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
59+ DateParseHandling = DateParseHandling.None,
60+ Converters =
61+ {
62+ new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
63+ },
64+ };
65+ }
66+}
67+#pragma warning restore CS8618
68+#pragma warning restore CS8601
69+#pragma warning restore CS8602
70+#pragma warning restore CS8603
71+#pragma warning restore CS8604
72+#pragma warning restore CS8625
73+#pragma warning restore CS8765
Aschema-csharp-SystemTextJsondefault / QuickType.cs+178 −0
@@ -0,0 +1,178 @@
1+// <auto-generated />
2+//
3+// To parse this JSON data, add NuGet 'System.Text.Json' then do:
4+//
5+// using QuickType;
6+//
7+// var topLevel = TopLevel.FromJson(jsonString);
8+#nullable enable
9+#pragma warning disable CS8618
10+#pragma warning disable CS8601
11+#pragma warning disable CS8602
12+#pragma warning disable CS8603
13+
14+namespace QuickType
15+{
16+ using System;
17+ using System.Collections.Generic;
18+
19+ using System.Text.Json;
20+ using System.Text.Json.Serialization;
21+ using System.Globalization;
22+
23+ public partial class TopLevel
24+ {
25+ [JsonPropertyName("animal")]
26+ public Dog? Animal { get; set; }
27+ }
28+
29+ public partial class Dog
30+ {
31+ [JsonRequired]
32+ [JsonPropertyName("discriminator")]
33+ public string Discriminator { get; set; }
34+
35+ [JsonPropertyName("foo")]
36+ public string? Foo { get; set; }
37+
38+ [JsonPropertyName("bar")]
39+ public string? Bar { get; set; }
40+ }
41+
42+ public partial class TopLevel
43+ {
44+ public static TopLevel FromJson(string json) => JsonSerializer.Deserialize<TopLevel>(json, QuickType.Converter.Settings);
45+ }
46+
47+ public static partial class Serialize
48+ {
49+ public static string ToJson(this TopLevel self) => JsonSerializer.Serialize(self, QuickType.Converter.Settings);
50+ }
51+
52+ internal static partial class Converter
53+ {
54+ public static readonly JsonSerializerOptions Settings = new(JsonSerializerDefaults.General)
55+ {
56+ Converters =
57+ {
58+ new DateOnlyConverter(),
59+ new TimeOnlyConverter(),
60+ IsoDateTimeOffsetConverter.Singleton
61+ },
62+ };
63+ }
64+
65+ public class DateOnlyConverter : JsonConverter<DateOnly>
66+ {
67+ private readonly string serializationFormat;
68+ public DateOnlyConverter() : this(null) { }
69+
70+ public DateOnlyConverter(string? serializationFormat)
71+ {
72+ this.serializationFormat = serializationFormat ?? "yyyy-MM-dd";
73+ }
74+
75+ public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
76+ {
77+ var value = reader.GetString();
78+ return DateOnly.Parse(value!);
79+ }
80+
81+ public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
82+ => writer.WriteStringValue(value.ToString(serializationFormat));
83+ }
84+
85+ public class TimeOnlyConverter : JsonConverter<TimeOnly>
86+ {
87+ private readonly string serializationFormat;
88+
89+ public TimeOnlyConverter() : this(null) { }
90+
91+ public TimeOnlyConverter(string? serializationFormat)
92+ {
93+ this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff";
94+ }
95+
96+ public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
97+ {
98+ var value = reader.GetString();
99+ return TimeOnly.Parse(value!);
100+ }
101+
102+ public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options)
103+ => writer.WriteStringValue(value.ToString(serializationFormat));
104+ }
105+
106+ internal class IsoDateTimeOffsetConverter : JsonConverter<DateTimeOffset>
107+ {
108+ public override bool CanConvert(Type t) => t == typeof(DateTimeOffset);
109+
110+ private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
111+
112+ private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind;
113+ private string? _dateTimeFormat;
114+ private CultureInfo? _culture;
115+
116+ public DateTimeStyles DateTimeStyles
117+ {
118+ get => _dateTimeStyles;
119+ set => _dateTimeStyles = value;
120+ }
121+
122+ public string? DateTimeFormat
123+ {
124+ get => _dateTimeFormat ?? string.Empty;
125+ set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value;
126+ }
127+
128+ public CultureInfo Culture
129+ {
130+ get => _culture ?? CultureInfo.CurrentCulture;
131+ set => _culture = value;
132+ }
133+
134+ public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
135+ {
136+ string text;
137+
138+
139+ if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
140+ || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
141+ {
142+ value = value.ToUniversalTime();
143+ }
144+
145+ text = value.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
146+
147+ writer.WriteStringValue(text);
148+ }
149+
150+ public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
151+ {
152+ string? dateText = reader.GetString();
153+
154+ if (string.IsNullOrEmpty(dateText) == false)
155+ {
156+ if (!string.IsNullOrEmpty(_dateTimeFormat))
157+ {
158+ return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
159+ }
160+ else
161+ {
162+ return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles);
163+ }
164+ }
165+ else
166+ {
167+ return default(DateTimeOffset);
168+ }
169+ }
170+
171+
172+ public static readonly IsoDateTimeOffsetConverter Singleton = new IsoDateTimeOffsetConverter();
173+ }
174+}
175+#pragma warning restore CS8618
176+#pragma warning restore CS8601
177+#pragma warning restore CS8602
178+#pragma warning restore CS8603
Aschema-csharpdefault / QuickType.cs+73 −0
@@ -0,0 +1,73 @@
1+// <auto-generated />
2+//
3+// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
4+//
5+// using QuickType;
6+//
7+// var topLevel = TopLevel.FromJson(jsonString);
8+#nullable enable
9+#pragma warning disable CS8618
10+#pragma warning disable CS8601
11+#pragma warning disable CS8602
12+#pragma warning disable CS8603
13+#pragma warning disable CS8604
14+#pragma warning disable CS8625
15+#pragma warning disable CS8765
16+
17+namespace QuickType
18+{
19+ using System;
20+ using System.Collections.Generic;
21+
22+ using System.Globalization;
23+ using Newtonsoft.Json;
24+ using Newtonsoft.Json.Converters;
25+
26+ public partial class TopLevel
27+ {
28+ [JsonProperty("animal")]
29+ public Dog? Animal { get; set; }
30+ }
31+
32+ public partial class Dog
33+ {
34+ [JsonProperty("discriminator", Required = Required.Always)]
35+ public string Discriminator { get; set; }
36+
37+ [JsonProperty("foo")]
38+ public string? Foo { get; set; }
39+
40+ [JsonProperty("bar")]
41+ public string? Bar { get; set; }
42+ }
43+
44+ public partial class TopLevel
45+ {
46+ public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings);
47+ }
48+
49+ public static partial class Serialize
50+ {
51+ public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
52+ }
53+
54+ internal static partial class Converter
55+ {
56+ public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
57+ {
58+ MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
59+ DateParseHandling = DateParseHandling.None,
60+ Converters =
61+ {
62+ new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
63+ },
64+ };
65+ }
66+}
67+#pragma warning restore CS8618
68+#pragma warning restore CS8601
69+#pragma warning restore CS8602
70+#pragma warning restore CS8603
71+#pragma warning restore CS8604
72+#pragma warning restore CS8625
73+#pragma warning restore CS8765
Aschema-dartdefault / TopLevel.dart+49 −0
@@ -0,0 +1,49 @@
1+// To parse this JSON data, do
2+//
3+// final topLevel = topLevelFromJson(jsonString);
4+
5+import 'dart:convert';
6+
7+TopLevel topLevelFromJson(String str) => TopLevel.fromJson(json.decode(str));
8+
9+String topLevelToJson(TopLevel data) => json.encode(data.toJson());
10+
11+class TopLevel {
12+ final Dog? animal;
13+
14+ TopLevel({
15+ this.animal,
16+ });
17+
18+ factory TopLevel.fromJson(Map<String, dynamic> json) => TopLevel(
19+ animal: json["animal"] == null ? null : Dog.fromJson(json["animal"]),
20+ );
21+
22+ Map<String, dynamic> toJson() => {
23+ "animal": animal?.toJson(),
24+ };
25+}
26+
27+class Dog {
28+ final String discriminator;
29+ final String? foo;
30+ final String? bar;
31+
32+ Dog({
33+ required this.discriminator,
34+ this.foo,
35+ this.bar,
36+ });
37+
38+ factory Dog.fromJson(Map<String, dynamic> json) => Dog(
39+ discriminator: json["discriminator"],
40+ foo: json["foo"],
41+ bar: json["bar"],
42+ );
43+
44+ Map<String, dynamic> toJson() => {
45+ "discriminator": discriminator,
46+ "foo": foo,
47+ "bar": bar,
48+ };
49+}
Aschema-elmdefault / QuickType.elm+73 −0
@@ -0,0 +1,73 @@
1+-- To decode the JSON data, add this file to your project, run
2+--
3+-- elm install NoRedInk/elm-json-decode-pipeline
4+--
5+-- add these imports
6+--
7+-- import Json.Decode exposing (decodeString)
8+-- import QuickType exposing (quickType)
9+--
10+-- and you're off to the races with
11+--
12+-- decodeString quickType myJsonString
13+
14+module QuickType exposing
15+ ( QuickType
16+ , quickTypeToString
17+ , quickType
18+ , Dog
19+ )
20+
21+import Json.Decode as Jdec
22+import Json.Decode.Pipeline as Jpipe
23+import Json.Encode as Jenc
24+import Dict exposing (Dict)
25+
26+type alias QuickType =
27+ { animal : Maybe Dog
28+ }
29+
30+type alias Dog =
31+ { discriminator : String
32+ , foo : Maybe String
33+ , bar : Maybe String
34+ }
35+
36+-- decoders and encoders
37+
38+quickTypeToString : QuickType -> String
39+quickTypeToString r = Jenc.encode 0 (encodeQuickType r)
40+
41+quickType : Jdec.Decoder QuickType
42+quickType =
43+ Jdec.succeed QuickType
44+ |> Jpipe.optional "animal" (Jdec.nullable dog) Nothing
45+
46+encodeQuickType : QuickType -> Jenc.Value
47+encodeQuickType x =
48+ Jenc.object
49+ [ ("animal", makeNullableEncoder encodeDog x.animal)
50+ ]
51+
52+dog : Jdec.Decoder Dog
53+dog =
54+ Jdec.succeed Dog
55+ |> Jpipe.required "discriminator" Jdec.string
56+ |> Jpipe.optional "foo" (Jdec.nullable Jdec.string) Nothing
57+ |> Jpipe.optional "bar" (Jdec.nullable Jdec.string) Nothing
58+
59+encodeDog : Dog -> Jenc.Value
60+encodeDog x =
61+ Jenc.object
62+ [ ("discriminator", Jenc.string x.discriminator)
63+ , ("foo", makeNullableEncoder Jenc.string x.foo)
64+ , ("bar", makeNullableEncoder Jenc.string x.bar)
65+ ]
66+
67+--- encoder helpers
68+
69+makeNullableEncoder : (a -> Jenc.Value) -> Maybe a -> Jenc.Value
70+makeNullableEncoder f m =
71+ case m of
72+ Just x -> f x
73+ Nothing -> Jenc.null
Aschema-flowdefault / TopLevel.js+199 −0
@@ -0,0 +1,199 @@
1+// @flow
2+
3+// To parse this data:
4+//
5+// const Convert = require("./TopLevel");
6+//
7+// const topLevel = Convert.toTopLevel(json);
8+//
9+// These functions will throw an error if the JSON doesn't
10+// match the expected interface, even if the JSON is valid.
11+
12+export type TopLevel = {
13+ animal?: Dog | null;
14+};
15+
16+export type Dog = {
17+ discriminator: string;
18+ foo?: null | string;
19+ bar?: null | string;
20+};
21+
22+// Converts JSON strings to/from your types
23+// and asserts the results of JSON.parse at runtime
24+function toTopLevel(json: string): TopLevel {
25+ return cast(JSON.parse(json), r("TopLevel"));
26+}
27+
28+function topLevelToJson(value: TopLevel): string {
29+ return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
30+}
31+
32+function invalidValue(typ: any, val: any, key: any, parent: any = '') {
33+ const prettyTyp = prettyTypeName(typ);
34+ const parentText = parent ? ` on ${parent}` : '';
35+ const keyText = key ? ` for key "${key}"` : '';
36+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
37+}
38+
39+function prettyTypeName(typ: any): string {
40+ if (Array.isArray(typ)) {
41+ if (typ.length === 2 && typ[0] === undefined) {
42+ return `an optional ${prettyTypeName(typ[1])}`;
43+ } else {
44+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
45+ }
46+ } else if (typeof typ === "object" && typ.literal !== undefined) {
47+ return typ.literal;
48+ } else {
49+ return typeof typ;
50+ }
51+}
52+
53+function jsonToJSProps(typ: any): any {
54+ if (typ.jsonToJS === undefined) {
55+ const map: any = {};
56+ typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
57+ typ.jsonToJS = map;
58+ }
59+ return typ.jsonToJS;
60+}
61+
62+function jsToJSONProps(typ: any): any {
63+ if (typ.jsToJSON === undefined) {
64+ const map: any = {};
65+ typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
66+ typ.jsToJSON = map;
67+ }
68+ return typ.jsToJSON;
69+}
70+
71+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
72+ function transformPrimitive(typ: string, val: any): any {
73+ if (typeof typ === typeof val) return val;
74+ return invalidValue(typ, val, key, parent);
75+ }
76+
77+ function transformUnion(typs: any[], val: any): any {
78+ // val must validate against one typ in typs
79+ const l = typs.length;
80+ for (let i = 0; i < l; i++) {
81+ const typ = typs[i];
82+ try {
83+ return transform(val, typ, getProps);
84+ } catch (_) {}
85+ }
86+ return invalidValue(typs, val, key, parent);
87+ }
88+
89+ function transformEnum(cases: string[], val: any): any {
90+ if (cases.indexOf(val) !== -1) return val;
91+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
92+ }
93+
94+ function transformArray(typ: any, val: any): any {
95+ // val must be an array with no invalid elements
96+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
97+ return val.map(el => transform(el, typ, getProps));
98+ }
99+
100+ function transformDate(val: any): any {
101+ if (val === null) {
102+ return null;
103+ }
104+ const d = new Date(val);
105+ if (isNaN(d.valueOf())) {
106+ return invalidValue(l("Date"), val, key, parent);
107+ }
108+ return d;
109+ }
110+
111+ function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
112+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
113+ return invalidValue(l(ref || "object"), val, key, parent);
114+ }
115+ const result: any = {};
116+ Object.getOwnPropertyNames(props).forEach(key => {
117+ const prop = props[key];
118+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
119+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
120+ });
121+ Object.getOwnPropertyNames(val).forEach(key => {
122+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
123+ result[key] = transform(val[key], additional, getProps, key, ref);
124+ }
125+ });
126+ return result;
127+ }
128+
129+ if (typ === "any") return val;
130+ if (typ === null) {
131+ if (val === null) return val;
132+ return invalidValue(typ, val, key, parent);
133+ }
134+ if (typ === false) return invalidValue(typ, val, key, parent);
135+ let ref: any = undefined;
136+ while (typeof typ === "object" && typ.ref !== undefined) {
137+ ref = typ.ref;
138+ typ = typeMap[typ.ref];
139+ }
140+ if (Array.isArray(typ)) return transformEnum(typ, val);
141+ if (typeof typ === "object") {
142+ return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
143+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
144+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
145+ : invalidValue(typ, val, key, parent);
146+ }
147+ // Numbers can be parsed by Date but shouldn't be.
148+ if (typ === Date && typeof val !== "number") return transformDate(val);
149+ return transformPrimitive(typ, val);
150+}
151+
152+function cast<T>(val: any, typ: any): T {
153+ return transform(val, typ, jsonToJSProps);
154+}
155+
156+function uncast<T>(val: T, typ: any): any {
157+ return transform(val, typ, jsToJSONProps);
158+}
159+
160+function l(typ: any) {
161+ return { literal: typ };
162+}
163+
164+function a(typ: any) {
165+ return { arrayItems: typ };
166+}
167+
168+function u(...typs: any[]) {
169+ return { unionMembers: typs };
170+}
171+
172+function o(props: any[], additional: any) {
173+ return { props, additional };
174+}
175+
176+function m(additional: any) {
177+ const props: any[] = [];
178+ return { props, additional };
179+}
180+
181+function r(name: string) {
182+ return { ref: name };
183+}
184+
185+const typeMap: any = {
186+ "TopLevel": o([
187+ { json: "animal", js: "animal", typ: u(undefined, u(r("Dog"), null)) },
188+ ], false),
189+ "Dog": o([
190+ { json: "discriminator", js: "discriminator", typ: "" },
191+ { json: "foo", js: "foo", typ: u(undefined, u(null, "")) },
192+ { json: "bar", js: "bar", typ: u(undefined, u(null, "")) },
193+ ], false),
194+};
195+
196+module.exports = {
197+ "topLevelToJson": topLevelToJson,
198+ "toTopLevel": toTopLevel,
199+};
Aschema-golangdefault / quicktype.go+29 −0
@@ -0,0 +1,29 @@
1+// Code generated from JSON Schema using quicktype. DO NOT EDIT.
2+// To parse and unparse this JSON data, add this code to your project and do:
3+//
4+// topLevel, err := UnmarshalTopLevel(bytes)
5+// bytes, err = topLevel.Marshal()
6+
7+package main
8+
9+import "encoding/json"
10+
11+func UnmarshalTopLevel(data []byte) (TopLevel, error) {
12+ var r TopLevel
13+ err := json.Unmarshal(data, &r)
14+ return r, err
15+}
16+
17+func (r *TopLevel) Marshal() ([]byte, error) {
18+ return json.Marshal(r)
19+}
20+
21+type TopLevel struct {
22+ Animal *Dog `json:"animal"`
23+}
24+
25+type Dog struct {
26+ Discriminator string `json:"discriminator"`
27+ Foo *string `json:"foo"`
28+ Bar *string `json:"bar"`
29+}
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / Converter.java+121 −0
@@ -0,0 +1,121 @@
1+// To use this code, add the following Maven dependency to your project:
2+//
3+//
4+// com.fasterxml.jackson.core : jackson-databind : 2.9.0
5+//
6+//
7+// Import this package:
8+//
9+// import io.quicktype.Converter;
10+//
11+// Then you can deserialize a JSON string with
12+//
13+// TopLevel data = Converter.fromJsonString(jsonString);
14+
15+package io.quicktype;
16+
17+import java.io.IOException;
18+import com.fasterxml.jackson.databind.*;
19+import com.fasterxml.jackson.databind.module.SimpleModule;
20+import com.fasterxml.jackson.core.JsonParser;
21+import com.fasterxml.jackson.core.JsonProcessingException;
22+import java.util.*;
23+import java.util.Date;
24+import java.text.SimpleDateFormat;
25+
26+public class Converter {
27+ // Date-time helpers
28+
29+ private static final String[] DATE_TIME_FORMATS = {
30+ "yyyy-MM-dd'T'HH:mm:ss.SX",
31+ "yyyy-MM-dd'T'HH:mm:ss.S",
32+ "yyyy-MM-dd'T'HH:mm:ssX",
33+ "yyyy-MM-dd'T'HH:mm:ss",
34+ "yyyy-MM-dd HH:mm:ss.SX",
35+ "yyyy-MM-dd HH:mm:ss.S",
36+ "yyyy-MM-dd HH:mm:ssX",
37+ "yyyy-MM-dd HH:mm:ss",
38+ "HH:mm:ss.SZ",
39+ "HH:mm:ss.S",
40+ "HH:mm:ssZ",
41+ "HH:mm:ss",
42+ "yyyy-MM-dd",
43+ };
44+
45+ public static Date parseAllDateTimeString(String str) {
46+ for (String format : DATE_TIME_FORMATS) {
47+ try {
48+ return new SimpleDateFormat(format).parse(str);
49+ } catch (Exception ex) {
50+ // Ignored
51+ }
52+ }
53+ return null;
54+ }
55+
56+ public static String serializeDateTime(Date datetime) {
57+ return new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ").format(datetime);
58+ }
59+
60+ public static String serializeDate(Date datetime) {
61+ return new SimpleDateFormat("yyyy-MM-dd").format(datetime);
62+ }
63+
64+ public static String serializeTime(Date datetime) {
65+ return new SimpleDateFormat("hh:mm:ssZ").format(datetime);
66+ }
67+ // Serialize/deserialize helpers
68+
69+ public static TopLevel fromJsonString(String json) throws IOException {
70+ return getObjectReader().readValue(json);
71+ }
72+
73+ public static String toJsonString(TopLevel obj) throws JsonProcessingException {
74+ return getObjectWriter().writeValueAsString(obj);
75+ }
76+
77+ private static ObjectReader reader;
78+ private static ObjectWriter writer;
79+
80+ private static void instantiateMapper() {
81+ ObjectMapper mapper = new ObjectMapper();
82+ mapper.findAndRegisterModules();
83+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
84+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
85+ SimpleModule module = new SimpleModule();
86+ module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
87+ @Override
88+ public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
89+ String value = jsonParser.getText();
90+ return Converter.parseAllDateTimeString(value);
91+ }
92+ });
93+ module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
94+ @Override
95+ public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
96+ String value = jsonParser.getText();
97+ return Converter.parseAllDateTimeString(value);
98+ }
99+ });
100+ module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
101+ @Override
102+ public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
103+ String value = jsonParser.getText();
104+ return Converter.parseAllDateTimeString(value);
105+ }
106+ });
107+ mapper.registerModule(module);
108+ reader = mapper.readerFor(TopLevel.class);
109+ writer = mapper.writerFor(TopLevel.class);
110+ }
111+
112+ private static ObjectReader getObjectReader() {
113+ if (reader == null) instantiateMapper();
114+ return reader;
115+ }
116+
117+ private static ObjectWriter getObjectWriter() {
118+ if (writer == null) instantiateMapper();
119+ return writer;
120+ }
121+}
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / Dog.java+24 −0
@@ -0,0 +1,24 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class Dog {
6+ private String discriminator;
7+ private String foo;
8+ private String bar;
9+
10+ @JsonProperty("discriminator")
11+ public String getDiscriminator() { return discriminator; }
12+ @JsonProperty("discriminator")
13+ public void setDiscriminator(String value) { this.discriminator = value; }
14+
15+ @JsonProperty("foo")
16+ public String getFoo() { return foo; }
17+ @JsonProperty("foo")
18+ public void setFoo(String value) { this.foo = value; }
19+
20+ @JsonProperty("bar")
21+ public String getBar() { return bar; }
22+ @JsonProperty("bar")
23+ public void setBar(String value) { this.bar = value; }
24+}
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / TopLevel.java+12 −0
@@ -0,0 +1,12 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class TopLevel {
6+ private Dog animal;
7+
8+ @JsonProperty("animal")
9+ public Dog getAnimal() { return animal; }
10+ @JsonProperty("animal")
11+ public void setAnimal(Dog value) { this.animal = value; }
12+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / Converter.java+101 −0
@@ -0,0 +1,101 @@
1+// To use this code, add the following Maven dependency to your project:
2+//
3+//
4+// com.fasterxml.jackson.core : jackson-databind : 2.9.0
5+// com.fasterxml.jackson.datatype : jackson-datatype-jsr310 : 2.9.0
6+//
7+// Import this package:
8+//
9+// import io.quicktype.Converter;
10+//
11+// Then you can deserialize a JSON string with
12+//
13+// TopLevel data = Converter.fromJsonString(jsonString);
14+
15+package io.quicktype;
16+
17+import java.io.IOException;
18+import com.fasterxml.jackson.databind.*;
19+import com.fasterxml.jackson.databind.module.SimpleModule;
20+import com.fasterxml.jackson.core.JsonParser;
21+import com.fasterxml.jackson.core.JsonProcessingException;
22+import java.util.*;
23+import java.time.LocalDate;
24+import java.time.OffsetDateTime;
25+import java.time.OffsetTime;
26+import java.time.ZoneOffset;
27+import java.time.ZonedDateTime;
28+import java.time.format.DateTimeFormatter;
29+import java.time.format.DateTimeFormatterBuilder;
30+import java.time.temporal.ChronoField;
31+
32+public class Converter {
33+ // Date-time helpers
34+
35+ private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
36+ .appendOptional(DateTimeFormatter.ISO_DATE_TIME)
37+ .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
38+ .appendOptional(DateTimeFormatter.ISO_INSTANT)
39+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX"))
40+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX"))
41+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
42+ .toFormatter()
43+ .withZone(ZoneOffset.UTC);
44+
45+ public static OffsetDateTime parseDateTimeString(String str) {
46+ return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();
47+ }
48+
49+ private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
50+ .appendOptional(DateTimeFormatter.ISO_TIME)
51+ .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)
52+ .parseDefaulting(ChronoField.YEAR, 2020)
53+ .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
54+ .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
55+ .toFormatter()
56+ .withZone(ZoneOffset.UTC);
57+
58+ public static OffsetTime parseTimeString(String str) {
59+ return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();
60+ }
61+ // Serialize/deserialize helpers
62+
63+ public static TopLevel fromJsonString(String json) throws IOException {
64+ return getObjectReader().readValue(json);
65+ }
66+
67+ public static String toJsonString(TopLevel obj) throws JsonProcessingException {
68+ return getObjectWriter().writeValueAsString(obj);
69+ }
70+
71+ private static ObjectReader reader;
72+ private static ObjectWriter writer;
73+
74+ private static void instantiateMapper() {
75+ ObjectMapper mapper = new ObjectMapper();
76+ mapper.findAndRegisterModules();
77+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
78+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
79+ SimpleModule module = new SimpleModule();
80+ module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
81+ @Override
82+ public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
83+ String value = jsonParser.getText();
84+ return Converter.parseDateTimeString(value);
85+ }
86+ });
87+ mapper.registerModule(module);
88+ reader = mapper.readerFor(TopLevel.class);
89+ writer = mapper.writerFor(TopLevel.class);
90+ }
91+
92+ private static ObjectReader getObjectReader() {
93+ if (reader == null) instantiateMapper();
94+ return reader;
95+ }
96+
97+ private static ObjectWriter getObjectWriter() {
98+ if (writer == null) instantiateMapper();
99+ return writer;
100+ }
101+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / Dog.java+24 −0
@@ -0,0 +1,24 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class Dog {
6+ private String discriminator;
7+ private String foo;
8+ private String bar;
9+
10+ @JsonProperty("discriminator")
11+ public String getDiscriminator() { return discriminator; }
12+ @JsonProperty("discriminator")
13+ public void setDiscriminator(String value) { this.discriminator = value; }
14+
15+ @JsonProperty("foo")
16+ public String getFoo() { return foo; }
17+ @JsonProperty("foo")
18+ public void setFoo(String value) { this.foo = value; }
19+
20+ @JsonProperty("bar")
21+ public String getBar() { return bar; }
22+ @JsonProperty("bar")
23+ public void setBar(String value) { this.bar = value; }
24+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / TopLevel.java+12 −0
@@ -0,0 +1,12 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class TopLevel {
6+ private Dog animal;
7+
8+ @JsonProperty("animal")
9+ public Dog getAnimal() { return animal; }
10+ @JsonProperty("animal")
11+ public void setAnimal(Dog value) { this.animal = value; }
12+}
Aschema-javadefault / src / main / java / io / quicktype / Converter.java+101 −0
@@ -0,0 +1,101 @@
1+// To use this code, add the following Maven dependency to your project:
2+//
3+//
4+// com.fasterxml.jackson.core : jackson-databind : 2.9.0
5+// com.fasterxml.jackson.datatype : jackson-datatype-jsr310 : 2.9.0
6+//
7+// Import this package:
8+//
9+// import io.quicktype.Converter;
10+//
11+// Then you can deserialize a JSON string with
12+//
13+// TopLevel data = Converter.fromJsonString(jsonString);
14+
15+package io.quicktype;
16+
17+import java.io.IOException;
18+import com.fasterxml.jackson.databind.*;
19+import com.fasterxml.jackson.databind.module.SimpleModule;
20+import com.fasterxml.jackson.core.JsonParser;
21+import com.fasterxml.jackson.core.JsonProcessingException;
22+import java.util.*;
23+import java.time.LocalDate;
24+import java.time.OffsetDateTime;
25+import java.time.OffsetTime;
26+import java.time.ZoneOffset;
27+import java.time.ZonedDateTime;
28+import java.time.format.DateTimeFormatter;
29+import java.time.format.DateTimeFormatterBuilder;
30+import java.time.temporal.ChronoField;
31+
32+public class Converter {
33+ // Date-time helpers
34+
35+ private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
36+ .appendOptional(DateTimeFormatter.ISO_DATE_TIME)
37+ .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
38+ .appendOptional(DateTimeFormatter.ISO_INSTANT)
39+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX"))
40+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX"))
41+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
42+ .toFormatter()
43+ .withZone(ZoneOffset.UTC);
44+
45+ public static OffsetDateTime parseDateTimeString(String str) {
46+ return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();
47+ }
48+
49+ private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
50+ .appendOptional(DateTimeFormatter.ISO_TIME)
51+ .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)
52+ .parseDefaulting(ChronoField.YEAR, 2020)
53+ .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
54+ .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
55+ .toFormatter()
56+ .withZone(ZoneOffset.UTC);
57+
58+ public static OffsetTime parseTimeString(String str) {
59+ return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();
60+ }
61+ // Serialize/deserialize helpers
62+
63+ public static TopLevel fromJsonString(String json) throws IOException {
64+ return getObjectReader().readValue(json);
65+ }
66+
67+ public static String toJsonString(TopLevel obj) throws JsonProcessingException {
68+ return getObjectWriter().writeValueAsString(obj);
69+ }
70+
71+ private static ObjectReader reader;
72+ private static ObjectWriter writer;
73+
74+ private static void instantiateMapper() {
75+ ObjectMapper mapper = new ObjectMapper();
76+ mapper.findAndRegisterModules();
77+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
78+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
79+ SimpleModule module = new SimpleModule();
80+ module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
81+ @Override
82+ public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
83+ String value = jsonParser.getText();
84+ return Converter.parseDateTimeString(value);
85+ }
86+ });
87+ mapper.registerModule(module);
88+ reader = mapper.readerFor(TopLevel.class);
89+ writer = mapper.writerFor(TopLevel.class);
90+ }
91+
92+ private static ObjectReader getObjectReader() {
93+ if (reader == null) instantiateMapper();
94+ return reader;
95+ }
96+
97+ private static ObjectWriter getObjectWriter() {
98+ if (writer == null) instantiateMapper();
99+ return writer;
100+ }
101+}
Aschema-javadefault / src / main / java / io / quicktype / Dog.java+24 −0
@@ -0,0 +1,24 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class Dog {
6+ private String discriminator;
7+ private String foo;
8+ private String bar;
9+
10+ @JsonProperty("discriminator")
11+ public String getDiscriminator() { return discriminator; }
12+ @JsonProperty("discriminator")
13+ public void setDiscriminator(String value) { this.discriminator = value; }
14+
15+ @JsonProperty("foo")
16+ public String getFoo() { return foo; }
17+ @JsonProperty("foo")
18+ public void setFoo(String value) { this.foo = value; }
19+
20+ @JsonProperty("bar")
21+ public String getBar() { return bar; }
22+ @JsonProperty("bar")
23+ public void setBar(String value) { this.bar = value; }
24+}
Aschema-javadefault / src / main / java / io / quicktype / TopLevel.java+12 −0
@@ -0,0 +1,12 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class TopLevel {
6+ private Dog animal;
7+
8+ @JsonProperty("animal")
9+ public Dog getAnimal() { return animal; }
10+ @JsonProperty("animal")
11+ public void setAnimal(Dog value) { this.animal = value; }
12+}
Aschema-javascriptdefault / TopLevel.js+187 −0
@@ -0,0 +1,187 @@
1+// To parse this data:
2+//
3+// const Convert = require("./TopLevel");
4+//
5+// const topLevel = Convert.toTopLevel(json);
6+//
7+// These functions will throw an error if the JSON doesn't
8+// match the expected interface, even if the JSON is valid.
9+
10+// Converts JSON strings to/from your types
11+// and asserts the results of JSON.parse at runtime
12+function toTopLevel(json) {
13+ return cast(JSON.parse(json), r("TopLevel"));
14+}
15+
16+function topLevelToJson(value) {
17+ return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
18+}
19+
20+function invalidValue(typ, val, key, parent = '') {
21+ const prettyTyp = prettyTypeName(typ);
22+ const parentText = parent ? ` on ${parent}` : '';
23+ const keyText = key ? ` for key "${key}"` : '';
24+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
25+}
26+
27+function prettyTypeName(typ) {
28+ if (Array.isArray(typ)) {
29+ if (typ.length === 2 && typ[0] === undefined) {
30+ return `an optional ${prettyTypeName(typ[1])}`;
31+ } else {
32+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
33+ }
34+ } else if (typeof typ === "object" && typ.literal !== undefined) {
35+ return typ.literal;
36+ } else {
37+ return typeof typ;
38+ }
39+}
40+
41+function jsonToJSProps(typ) {
42+ if (typ.jsonToJS === undefined) {
43+ const map = {};
44+ typ.props.forEach((p) => map[p.json] = { key: p.js, typ: p.typ });
45+ typ.jsonToJS = map;
46+ }
47+ return typ.jsonToJS;
48+}
49+
50+function jsToJSONProps(typ) {
51+ if (typ.jsToJSON === undefined) {
52+ const map = {};
53+ typ.props.forEach((p) => map[p.js] = { key: p.json, typ: p.typ });
54+ typ.jsToJSON = map;
55+ }
56+ return typ.jsToJSON;
57+}
58+
59+function transform(val, typ, getProps, key = '', parent = '') {
60+ function transformPrimitive(typ, val) {
61+ if (typeof typ === typeof val) return val;
62+ return invalidValue(typ, val, key, parent);
63+ }
64+
65+ function transformUnion(typs, val) {
66+ // val must validate against one typ in typs
67+ const l = typs.length;
68+ for (let i = 0; i < l; i++) {
69+ const typ = typs[i];
70+ try {
71+ return transform(val, typ, getProps);
72+ } catch (_) {}
73+ }
74+ return invalidValue(typs, val, key, parent);
75+ }
76+
77+ function transformEnum(cases, val) {
78+ if (cases.indexOf(val) !== -1) return val;
79+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
80+ }
81+
82+ function transformArray(typ, val) {
83+ // val must be an array with no invalid elements
84+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
85+ return val.map(el => transform(el, typ, getProps));
86+ }
87+
88+ function transformDate(val) {
89+ if (val === null) {
90+ return null;
91+ }
92+ const d = new Date(val);
93+ if (isNaN(d.valueOf())) {
94+ return invalidValue(l("Date"), val, key, parent);
95+ }
96+ return d;
97+ }
98+
99+ function transformObject(props, additional, val) {
100+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
101+ return invalidValue(l(ref || "object"), val, key, parent);
102+ }
103+ const result = {};
104+ Object.getOwnPropertyNames(props).forEach(key => {
105+ const prop = props[key];
106+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
107+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
108+ });
109+ Object.getOwnPropertyNames(val).forEach(key => {
110+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
111+ result[key] = transform(val[key], additional, getProps, key, ref);
112+ }
113+ });
114+ return result;
115+ }
116+
117+ if (typ === "any") return val;
118+ if (typ === null) {
119+ if (val === null) return val;
120+ return invalidValue(typ, val, key, parent);
121+ }
122+ if (typ === false) return invalidValue(typ, val, key, parent);
123+ let ref = undefined;
124+ while (typeof typ === "object" && typ.ref !== undefined) {
125+ ref = typ.ref;
126+ typ = typeMap[typ.ref];
127+ }
128+ if (Array.isArray(typ)) return transformEnum(typ, val);
129+ if (typeof typ === "object") {
130+ return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
131+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
132+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
133+ : invalidValue(typ, val, key, parent);
134+ }
135+ // Numbers can be parsed by Date but shouldn't be.
136+ if (typ === Date && typeof val !== "number") return transformDate(val);
137+ return transformPrimitive(typ, val);
138+}
139+
140+function cast(val, typ) {
141+ return transform(val, typ, jsonToJSProps);
142+}
143+
144+function uncast(val, typ) {
145+ return transform(val, typ, jsToJSONProps);
146+}
147+
148+function l(typ) {
149+ return { literal: typ };
150+}
151+
152+function a(typ) {
153+ return { arrayItems: typ };
154+}
155+
156+function u(...typs) {
157+ return { unionMembers: typs };
158+}
159+
160+function o(props, additional) {
161+ return { props, additional };
162+}
163+
164+function m(additional) {
165+ const props = [];
166+ return { props, additional };
167+}
168+
169+function r(name) {
170+ return { ref: name };
171+}
172+
173+const typeMap = {
174+ "TopLevel": o([
175+ { json: "animal", js: "animal", typ: u(undefined, u(r("Dog"), null)) },
176+ ], false),
177+ "Dog": o([
178+ { json: "discriminator", js: "discriminator", typ: "" },
179+ { json: "foo", js: "foo", typ: u(undefined, u(null, "")) },
180+ { json: "bar", js: "bar", typ: u(undefined, u(null, "")) },
181+ ], false),
182+};
183+
184+module.exports = {
185+ "topLevelToJson": topLevelToJson,
186+ "toTopLevel": toTopLevel,
187+};
Aschema-kotlin-jacksondefault / TopLevel.kt+37 −0
@@ -0,0 +1,37 @@
1+// To parse the JSON, install jackson-module-kotlin and do:
2+//
3+// val topLevel = TopLevel.fromJson(jsonString)
4+
5+package quicktype
6+
7+import com.fasterxml.jackson.annotation.*
8+import com.fasterxml.jackson.core.*
9+import com.fasterxml.jackson.databind.*
10+import com.fasterxml.jackson.databind.deser.std.StdDeserializer
11+import com.fasterxml.jackson.databind.module.SimpleModule
12+import com.fasterxml.jackson.databind.node.*
13+import com.fasterxml.jackson.databind.ser.std.StdSerializer
14+import com.fasterxml.jackson.module.kotlin.*
15+
16+val mapper = jacksonObjectMapper().apply {
17+ propertyNamingStrategy = PropertyNamingStrategy.LOWER_CAMEL_CASE
18+ setSerializationInclusion(JsonInclude.Include.NON_NULL)
19+}
20+
21+data class TopLevel (
22+ val animal: Dog? = null
23+) {
24+ fun toJson() = mapper.writeValueAsString(this)
25+
26+ companion object {
27+ fun fromJson(json: String) = mapper.readValue<TopLevel>(json)
28+ }
29+}
30+
31+data class Dog (
32+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
33+ val discriminator: String,
34+
35+ val foo: String? = null,
36+ val bar: String? = null
37+)
Aschema-kotlindefault / TopLevel.kt+25 −0
@@ -0,0 +1,25 @@
1+// To parse the JSON, install Klaxon and do:
2+//
3+// val topLevel = TopLevel.fromJson(jsonString)
4+
5+package quicktype
6+
7+import com.beust.klaxon.*
8+
9+private val klaxon = Klaxon()
10+
11+data class TopLevel (
12+ val animal: Dog? = null
13+) {
14+ public fun toJson() = klaxon.toJsonString(this)
15+
16+ companion object {
17+ public fun fromJson(json: String) = klaxon.parse<TopLevel>(json)
18+ }
19+}
20+
21+data class Dog (
22+ val discriminator: String,
23+ val foo: String? = null,
24+ val bar: String? = null
25+)
Aschema-kotlinxdefault / TopLevel.kt+23 −0
@@ -0,0 +1,23 @@
1+// To parse the JSON, install kotlin's serialization plugin and do:
2+//
3+// val json = Json { allowStructuredMapKeys = true }
4+// val topLevel = json.parse(TopLevel.serializer(), jsonString)
5+
6+package quicktype
7+
8+import kotlinx.serialization.*
9+import kotlinx.serialization.json.*
10+import kotlinx.serialization.descriptors.*
11+import kotlinx.serialization.encoding.*
12+
13+@Serializable
14+data class TopLevel (
15+ val animal: Dog? = null
16+)
17+
18+@Serializable
19+data class Dog (
20+ val discriminator: String,
21+ val foo: String? = null,
22+ val bar: String? = null
23+)
Aschema-phpdefault / TopLevel.php+337 −0
@@ -0,0 +1,337 @@
1+<?php
2+declare(strict_types=1);
3+
4+// This is an autogenerated file:TopLevel
5+
6+class TopLevel {
7+ private ?Dog $animal; // json:animal Optional
8+
9+ /**
10+ * @param Dog|null $animal
11+ */
12+ public function __construct(?Dog $animal) {
13+ $this->animal = $animal;
14+ }
15+
16+ /**
17+ * @param ?stdClass $value
18+ * @throws Exception
19+ * @return ?Dog
20+ */
21+ public static function fromAnimal(?stdClass $value): ?Dog {
22+ if (!is_null($value)) {
23+ return Dog::from($value); /*class*/
24+ } else {
25+ return null;
26+ }
27+ }
28+
29+ /**
30+ * @throws Exception
31+ * @return ?stdClass
32+ */
33+ public function toAnimal(): ?stdClass {
34+ if (TopLevel::validateAnimal($this->animal)) {
35+ if (!is_null($this->animal)) {
36+ return $this->animal->to(); /*class*/
37+ } else {
38+ return null;
39+ }
40+ }
41+ throw new Exception('never get to this TopLevel::animal');
42+ }
43+
44+ /**
45+ * @param Dog|null
46+ * @return bool
47+ * @throws Exception
48+ */
49+ public static function validateAnimal(?Dog $value): bool {
50+ if (!is_null($value)) {
51+ $value->validate();
52+ }
53+ return true;
54+ }
55+
56+ /**
57+ * @throws Exception
58+ * @return ?Dog
59+ */
60+ public function getAnimal(): ?Dog {
61+ if (TopLevel::validateAnimal($this->animal)) {
62+ return $this->animal;
63+ }
64+ throw new Exception('never get to getAnimal TopLevel::animal');
65+ }
66+
67+ /**
68+ * @return ?Dog
69+ */
70+ public static function sampleAnimal(): ?Dog {
71+ return Dog::sample(); /*31:animal*/
72+ }
73+
74+ /**
75+ * @throws Exception
76+ * @return bool
77+ */
78+ public function validate(): bool {
79+ return TopLevel::validateAnimal($this->animal);
80+ }
81+
82+ /**
83+ * @return stdClass
84+ * @throws Exception
85+ */
86+ public function to(): stdClass {
87+ $out = new stdClass();
88+ $out->{'animal'} = $this->toAnimal();
89+ return $out;
90+ }
91+
92+ /**
93+ * @param stdClass $obj
94+ * @return TopLevel
95+ * @throws Exception
96+ */
97+ public static function from(stdClass $obj): TopLevel {
98+ return new TopLevel(
99+ TopLevel::fromAnimal($obj->{'animal'})
100+ );
101+ }
102+
103+ /**
104+ * @return TopLevel
105+ */
106+ public static function sample(): TopLevel {
107+ return new TopLevel(
108+ TopLevel::sampleAnimal()
109+ );
110+ }
111+}
112+
113+// This is an autogenerated file:Dog
114+
115+class Dog {
116+ private string $discriminator; // json:discriminator Required
117+ private ?string $foo; // json:foo Optional
118+ private ?string $bar; // json:bar Optional
119+
120+ /**
121+ * @param string $discriminator
122+ * @param string|null $foo
123+ * @param string|null $bar
124+ */
125+ public function __construct(string $discriminator, ?string $foo, ?string $bar) {
126+ $this->discriminator = $discriminator;
127+ $this->foo = $foo;
128+ $this->bar = $bar;
129+ }
130+
131+ /**
132+ * @param string $value
133+ * @throws Exception
134+ * @return string
135+ */
136+ public static function fromDiscriminator(string $value): string {
137+ return $value; /*string*/
138+ }
139+
140+ /**
141+ * @throws Exception
142+ * @return string
143+ */
144+ public function toDiscriminator(): string {
145+ if (Dog::validateDiscriminator($this->discriminator)) {
146+ return $this->discriminator; /*string*/
147+ }
148+ throw new Exception('never get to this Dog::discriminator');
149+ }
150+
151+ /**
152+ * @param string
153+ * @return bool
154+ * @throws Exception
155+ */
156+ public static function validateDiscriminator(string $value): bool {
157+ return true;
158+ }
159+
160+ /**
161+ * @throws Exception
162+ * @return string
163+ */
164+ public function getDiscriminator(): string {
165+ if (Dog::validateDiscriminator($this->discriminator)) {
166+ return $this->discriminator;
167+ }
168+ throw new Exception('never get to getDiscriminator Dog::discriminator');
169+ }
170+
171+ /**
172+ * @return string
173+ */
174+ public static function sampleDiscriminator(): string {
175+ return 'Dog::discriminator::31'; /*31:discriminator*/
176+ }
177+
178+ /**
179+ * @param ?string $value
180+ * @throws Exception
181+ * @return ?string
182+ */
183+ public static function fromFoo(?string $value): ?string {
184+ if (!is_null($value)) {
185+ return $value; /*string*/
186+ } else {
187+ return null;
188+ }
189+ }
190+
191+ /**
192+ * @throws Exception
193+ * @return ?string
194+ */
195+ public function toFoo(): ?string {
196+ if (Dog::validateFoo($this->foo)) {
197+ if (!is_null($this->foo)) {
198+ return $this->foo; /*string*/
199+ } else {
200+ return null;
201+ }
202+ }
203+ throw new Exception('never get to this Dog::foo');
204+ }
205+
206+ /**
207+ * @param string|null
208+ * @return bool
209+ * @throws Exception
210+ */
211+ public static function validateFoo(?string $value): bool {
212+ if (!is_null($value)) {
213+ }
214+ return true;
215+ }
216+
217+ /**
218+ * @throws Exception
219+ * @return ?string
220+ */
221+ public function getFoo(): ?string {
222+ if (Dog::validateFoo($this->foo)) {
223+ return $this->foo;
224+ }
225+ throw new Exception('never get to getFoo Dog::foo');
226+ }
227+
228+ /**
229+ * @return ?string
230+ */
231+ public static function sampleFoo(): ?string {
232+ return 'Dog::foo::32'; /*32:foo*/
233+ }
234+
235+ /**
236+ * @param ?string $value
237+ * @throws Exception
238+ * @return ?string
239+ */
240+ public static function fromBar(?string $value): ?string {
241+ if (!is_null($value)) {
242+ return $value; /*string*/
243+ } else {
244+ return null;
245+ }
246+ }
247+
248+ /**
249+ * @throws Exception
250+ * @return ?string
251+ */
252+ public function toBar(): ?string {
253+ if (Dog::validateBar($this->bar)) {
254+ if (!is_null($this->bar)) {
255+ return $this->bar; /*string*/
256+ } else {
257+ return null;
258+ }
259+ }
260+ throw new Exception('never get to this Dog::bar');
261+ }
262+
263+ /**
264+ * @param string|null
265+ * @return bool
266+ * @throws Exception
267+ */
268+ public static function validateBar(?string $value): bool {
269+ if (!is_null($value)) {
270+ }
271+ return true;
272+ }
273+
274+ /**
275+ * @throws Exception
276+ * @return ?string
277+ */
278+ public function getBar(): ?string {
279+ if (Dog::validateBar($this->bar)) {
280+ return $this->bar;
281+ }
282+ throw new Exception('never get to getBar Dog::bar');
283+ }
284+
285+ /**
286+ * @return ?string
287+ */
288+ public static function sampleBar(): ?string {
289+ return 'Dog::bar::33'; /*33:bar*/
290+ }
291+
292+ /**
293+ * @throws Exception
294+ * @return bool
295+ */
296+ public function validate(): bool {
297+ return Dog::validateDiscriminator($this->discriminator)
298+ || Dog::validateFoo($this->foo)
299+ || Dog::validateBar($this->bar);
300+ }
301+
302+ /**
303+ * @return stdClass
304+ * @throws Exception
305+ */
306+ public function to(): stdClass {
307+ $out = new stdClass();
308+ $out->{'discriminator'} = $this->toDiscriminator();
309+ $out->{'foo'} = $this->toFoo();
310+ $out->{'bar'} = $this->toBar();
311+ return $out;
312+ }
313+
314+ /**
315+ * @param stdClass $obj
316+ * @return Dog
317+ * @throws Exception
318+ */
319+ public static function from(stdClass $obj): Dog {
320+ return new Dog(
321+ Dog::fromDiscriminator($obj->{'discriminator'})
322+ ,Dog::fromFoo($obj->{'foo'})
323+ ,Dog::fromBar($obj->{'bar'})
324+ );
325+ }
326+
327+ /**
328+ * @return Dog
329+ */
330+ public static function sample(): Dog {
331+ return new Dog(
332+ Dog::sampleDiscriminator()
333+ ,Dog::sampleFoo()
334+ ,Dog::sampleBar()
335+ );
336+ }
337+}
Aschema-pikedefault / TopLevel.pmod+59 −0
@@ -0,0 +1,59 @@
1+// This source has been automatically generated by quicktype.
2+// ( https://github.com/quicktype/quicktype )
3+//
4+// To use this code, simply import it into your project as a Pike module.
5+// To JSON-encode your object, you can pass it to `Standards.JSON.encode`
6+// or call `encode_json` on it.
7+//
8+// To decode a JSON string, first pass it to `Standards.JSON.decode`,
9+// and then pass the result to `<YourClass>_from_JSON`.
10+// It will return an instance of <YourClass>.
11+// Bear in mind that these functions have unexpected behavior,
12+// and will likely throw an error, if the JSON string does not
13+// match the expected interface, even if the JSON itself is valid.
14+
15+class TopLevel {
16+ Dog|mixed animal; // json: "animal"
17+
18+ string encode_json() {
19+ mapping(string:mixed) json = ([
20+ "animal" : animal,
21+ ]);
22+
23+ return Standards.JSON.encode(json);
24+ }
25+}
26+
27+TopLevel TopLevel_from_JSON(mixed json) {
28+ TopLevel retval = TopLevel();
29+
30+ retval.animal = json["animal"];
31+
32+ return retval;
33+}
34+
35+class Dog {
36+ string discriminator; // json: "discriminator"
37+ mixed|string foo; // json: "foo"
38+ mixed|string bar; // json: "bar"
39+
40+ string encode_json() {
41+ mapping(string:mixed) json = ([
42+ "discriminator" : discriminator,
43+ "foo" : foo,
44+ "bar" : bar,
45+ ]);
46+
47+ return Standards.JSON.encode(json);
48+ }
49+}
50+
51+Dog Dog_from_JSON(mixed json) {
52+ Dog retval = Dog();
53+
54+ retval.discriminator = json["discriminator"];
55+ retval.foo = json["foo"];
56+ retval.bar = json["bar"];
57+
58+ return retval;
59+}
Aschema-pythondefault / quicktype.py+78 −0
@@ -0,0 +1,78 @@
1+from dataclasses import dataclass
2+from typing import Any, TypeVar, Type, cast
3+
4+
5+T = TypeVar("T")
6+
7+
8+def from_str(x: Any) -> str:
9+ assert isinstance(x, str)
10+ return x
11+
12+
13+def from_none(x: Any) -> Any:
14+ assert x is None
15+ return x
16+
17+
18+def from_union(fs, x):
19+ for f in fs:
20+ try:
21+ return f(x)
22+ except:
23+ pass
24+ assert False
25+
26+
27+def to_class(c: Type[T], x: Any) -> dict:
28+ assert isinstance(x, c)
29+ return cast(Any, x).to_dict()
30+
31+
32+@dataclass
33+class Dog:
34+ discriminator: str
35+ foo: str | None = None
36+ bar: str | None = None
37+
38+ @staticmethod
39+ def from_dict(obj: Any) -> 'Dog':
40+ assert isinstance(obj, dict)
41+ discriminator = from_str(obj.get("discriminator"))
42+ foo = from_union([from_none, from_str], obj.get("foo"))
43+ bar = from_union([from_none, from_str], obj.get("bar"))
44+ return Dog(discriminator, foo, bar)
45+
46+ def to_dict(self) -> dict:
47+ result: dict = {}
48+ result["discriminator"] = from_str(self.discriminator)
49+ if self.foo is not None:
50+ result["foo"] = from_union([from_none, from_str], self.foo)
51+ if self.bar is not None:
52+ result["bar"] = from_union([from_none, from_str], self.bar)
53+ return result
54+
55+
56+@dataclass
57+class TopLevel:
58+ animal: Dog | None = None
59+
60+ @staticmethod
61+ def from_dict(obj: Any) -> 'TopLevel':
62+ assert isinstance(obj, dict)
63+ animal = from_union([Dog.from_dict, from_none], obj.get("animal"))
64+ return TopLevel(animal)
65+
66+ def to_dict(self) -> dict:
67+ result: dict = {}
68+ if self.animal is not None:
69+ result["animal"] = from_union([lambda x: to_class(Dog, x), from_none], self.animal)
70+ return result
71+
72+
73+def top_level_from_dict(s: Any) -> TopLevel:
74+ return TopLevel.from_dict(s)
75+
76+
77+def top_level_to_dict(x: TopLevel) -> Any:
78+ return to_class(TopLevel, x)
Aschema-rubydefault / TopLevel.rb+77 −0
@@ -0,0 +1,77 @@
1+# This code may look unusually verbose for Ruby (and it is), but
2+# it performs some subtle and complex validation of JSON data.
3+#
4+# To parse this JSON, add 'dry-struct' and 'dry-types' gems, then do:
5+#
6+# top_level = TopLevel.from_json! "{…}"
7+# puts top_level.animal&.discriminator
8+#
9+# If from_json! succeeds, the value returned matches the schema.
10+
11+require 'json'
12+require 'dry-types'
13+require 'dry-struct'
14+
15+module Types
16+ include Dry.Types(default: :nominal)
17+
18+ Nil = Strict::Nil
19+ Hash = Strict::Hash
20+ String = Strict::String
21+end
22+
23+class Dog < Dry::Struct
24+ attribute :discriminator, Types::String
25+ attribute :foo, Types::String.optional.optional
26+ attribute :bar, Types::String.optional.optional
27+
28+ def self.from_dynamic!(d)
29+ d = Types::Hash[d]
30+ new(
31+ discriminator: d.fetch("discriminator"),
32+ foo: d["foo"],
33+ bar: d["bar"],
34+ )
35+ end
36+
37+ def self.from_json!(json)
38+ from_dynamic!(JSON.parse(json))
39+ end
40+
41+ def to_dynamic
42+ {
43+ "discriminator" => discriminator,
44+ "foo" => foo,
45+ "bar" => bar,
46+ }
47+ end
48+
49+ def to_json(options = nil)
50+ JSON.generate(to_dynamic, options)
51+ end
52+end
53+
54+class TopLevel < Dry::Struct
55+ attribute :animal, Dog.optional.optional
56+
57+ def self.from_dynamic!(d)
58+ d = Types::Hash[d]
59+ new(
60+ animal: d["animal"] ? Dog.from_dynamic!(d["animal"]) : nil,
61+ )
62+ end
63+
64+ def self.from_json!(json)
65+ from_dynamic!(JSON.parse(json))
66+ end
67+
68+ def to_dynamic
69+ {
70+ "animal" => animal&.to_dynamic,
71+ }
72+ end
73+
74+ def to_json(options = nil)
75+ JSON.generate(to_dynamic, options)
76+ end
77+end
Aschema-rustdefault / module_under_test.rs+28 −0
@@ -0,0 +1,28 @@
1+// Example code that deserializes and serializes the model.
2+// extern crate serde;
3+// #[macro_use]
4+// extern crate serde_derive;
5+// extern crate serde_json;
6+//
7+// use generated_module::TopLevel;
8+//
9+// fn main() {
10+// let json = r#"{"answer": 42}"#;
11+// let model: TopLevel = serde_json::from_str(&json).unwrap();
12+// }
13+
14+use serde::{Serialize, Deserialize};
15+
16+#[derive(Debug, Clone, Serialize, Deserialize)]
17+pub struct TopLevel {
18+ pub animal: Option<Dog>,
19+}
20+
21+#[derive(Debug, Clone, Serialize, Deserialize)]
22+pub struct Dog {
23+ pub discriminator: String,
24+
25+ pub foo: Option<String>,
26+
27+ pub bar: Option<String>,
28+}
Aschema-scala3-upickledefault / TopLevel.scala+76 −0
@@ -0,0 +1,76 @@
1+package quicktype
2+
3+// Custom pickler so that missing keys and JSON nulls both read as None,
4+// and None is left out when writing (upickle's default for Option is a
5+// JSON array).
6+object OptionPickler extends upickle.AttributeTagged:
7+ import upickle.default.Writer
8+ import upickle.default.Reader
9+ override implicit def OptionWriter[T: Writer]: Writer[Option[T]] =
10+ implicitly[Writer[T]].comap[Option[T]] {
11+ case None => null.asInstanceOf[T]
12+ case Some(x) => x
13+ }
14+
15+ override implicit def OptionReader[T: Reader]: Reader[Option[T]] = {
16+ new Reader.Delegate[Any, Option[T]](implicitly[Reader[T]].map(Some(_))){
17+ override def visitNull(index: Int) = None
18+ }
19+ }
20+end OptionPickler
21+
22+// If a union has a null in, then we'll need this too...
23+type NullValue = None.type
24+given OptionPickler.ReadWriter[NullValue] = OptionPickler.readwriter[ujson.Value].bimap[NullValue](
25+ _ => ujson.Null,
26+ json => if json.isNull then None else throw new upickle.core.Abort("not null")
27+)
28+
29+object JsonExt:
30+ val valueReader = OptionPickler.readwriter[ujson.Value]
31+
32+ // upickle's built-in primitive readers are lenient -- the numeric and
33+ // boolean readers accept strings, and the string reader accepts
34+ // numbers and booleans -- so untagged unions need strict readers to
35+ // pick the right member.
36+ val strictString: OptionPickler.Reader[String] = valueReader.map {
37+ case ujson.Str(s) => s
38+ case json => throw new upickle.core.Abort("expected string, got " + json)
39+ }
40+ val strictLong: OptionPickler.Reader[Long] = valueReader.map {
41+ case ujson.Num(n) if n.isWhole => n.toLong
42+ case json => throw new upickle.core.Abort("expected integer, got " + json)
43+ }
44+ val strictDouble: OptionPickler.Reader[Double] = valueReader.map {
45+ case ujson.Num(n) => n
46+ case json => throw new upickle.core.Abort("expected number, got " + json)
47+ }
48+ val strictBoolean: OptionPickler.Reader[Boolean] = valueReader.map {
49+ case ujson.Bool(b) => b
50+ case json => throw new upickle.core.Abort("expected boolean, got " + json)
51+ }
52+
53+ def badMerge[T](r1: => OptionPickler.Reader[?], rest: OptionPickler.Reader[?]*): OptionPickler.Reader[T] = valueReader.map { json =>
54+ var t: T | Null = null
55+ val stack = Vector.newBuilder[Throwable]
56+ (r1 +: rest).foreach { reader =>
57+ if t == null then
58+ try
59+ t = OptionPickler.read[T](json, trace = true)(using reader.asInstanceOf[OptionPickler.Reader[T]])
60+ catch
61+ case exc => stack += exc
62+ }
63+ if t != null then t.nn else throw new Exception(json.toString(), stack.result().headOption.getOrElse(null))
64+ }
65+end JsonExt
66+
67+
68+case class TopLevel (
69+ val animal : Option[Dog] = None
70+) derives OptionPickler.ReadWriter
71+
72+case class Dog (
73+ val discriminator : String,
74+ val foo : Option[String] = None,
75+ val bar : Option[String] = None
76+) derives OptionPickler.ReadWriter
Aschema-scala3default / TopLevel.scala+18 −0
@@ -0,0 +1,18 @@
1+package quicktype
2+
3+import io.circe.syntax._
4+import io.circe._
5+import cats.syntax.functor._
6+
7+// If a union has a null in, then we'll need this too...
8+type NullValue = None.type
9+
10+case class TopLevel (
11+ val animal : Option[Dog] = None
12+) derives Encoder.AsObject, Decoder
13+
14+case class Dog (
15+ val discriminator : String,
16+ val foo : Option[String] = None,
17+ val bar : Option[String] = None
18+) derives Encoder.AsObject, Decoder
Aschema-schemadefault / TopLevel.schema+57 −0
@@ -0,0 +1,57 @@
1+{
2+ "$schema": "http://json-schema.org/draft-06/schema#",
3+ "$ref": "#/definitions/TopLevel",
4+ "definitions": {
5+ "TopLevel": {
6+ "type": "object",
7+ "additionalProperties": false,
8+ "properties": {
9+ "animal": {
10+ "anyOf": [
11+ {
12+ "$ref": "#/definitions/Dog"
13+ },
14+ {
15+ "type": "null"
16+ }
17+ ]
18+ }
19+ },
20+ "required": [],
21+ "title": "TopLevel"
22+ },
23+ "Dog": {
24+ "type": "object",
25+ "additionalProperties": false,
26+ "properties": {
27+ "discriminator": {
28+ "type": "string"
29+ },
30+ "foo": {
31+ "anyOf": [
32+ {
33+ "type": "null"
34+ },
35+ {
36+ "type": "string"
37+ }
38+ ]
39+ },
40+ "bar": {
41+ "anyOf": [
42+ {
43+ "type": "null"
44+ },
45+ {
46+ "type": "string"
47+ }
48+ ]
49+ }
50+ },
51+ "required": [
52+ "discriminator"
53+ ],
54+ "title": "Dog"
55+ }
56+ }
57+}
Aschema-typescript-zoddefault / TopLevel.ts+14 −0
@@ -0,0 +1,14 @@
1+import * as z from "zod";
2+
3+
4+export const DogSchema = z.object({
5+ "discriminator": z.string(),
6+ "foo": z.union([z.null(), z.string()]).optional(),
7+ "bar": z.union([z.null(), z.string()]).optional(),
8+});
9+export type Dog = z.infer<typeof DogSchema>;
10+
11+export const TopLevelSchema = z.object({
12+ "animal": z.union([z.null(), DogSchema]).optional(),
13+});
14+export type TopLevel = z.infer<typeof TopLevelSchema>;
Aschema-typescriptdefault / TopLevel.ts+194 −0
@@ -0,0 +1,194 @@
1+// To parse this data:
2+//
3+// import { Convert, TopLevel } from "./TopLevel";
4+//
5+// const topLevel = Convert.toTopLevel(json);
6+//
7+// These functions will throw an error if the JSON doesn't
8+// match the expected interface, even if the JSON is valid.
9+
10+export interface TopLevel {
11+ animal?: Dog | null;
12+}
13+
14+export interface Dog {
15+ discriminator: string;
16+ foo?: null | string;
17+ bar?: null | string;
18+}
19+
20+// Converts JSON strings to/from your types
21+// and asserts the results of JSON.parse at runtime
22+export class Convert {
23+ public static toTopLevel(json: string): TopLevel {
24+ return cast(JSON.parse(json), r("TopLevel"));
25+ }
26+
27+ public static topLevelToJson(value: TopLevel): string {
28+ return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
29+ }
30+}
31+
32+function invalidValue(typ: any, val: any, key: any, parent: any = ''): never {
33+ const prettyTyp = prettyTypeName(typ);
34+ const parentText = parent ? ` on ${parent}` : '';
35+ const keyText = key ? ` for key "${key}"` : '';
36+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
37+}
38+
39+function prettyTypeName(typ: any): string {
40+ if (Array.isArray(typ)) {
41+ if (typ.length === 2 && typ[0] === undefined) {
42+ return `an optional ${prettyTypeName(typ[1])}`;
43+ } else {
44+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
45+ }
46+ } else if (typeof typ === "object" && typ.literal !== undefined) {
47+ return typ.literal;
48+ } else {
49+ return typeof typ;
50+ }
51+}
52+
53+function jsonToJSProps(typ: any): any {
54+ if (typ.jsonToJS === undefined) {
55+ const map: any = {};
56+ typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
57+ typ.jsonToJS = map;
58+ }
59+ return typ.jsonToJS;
60+}
61+
62+function jsToJSONProps(typ: any): any {
63+ if (typ.jsToJSON === undefined) {
64+ const map: any = {};
65+ typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
66+ typ.jsToJSON = map;
67+ }
68+ return typ.jsToJSON;
69+}
70+
71+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
72+ function transformPrimitive(typ: string, val: any): any {
73+ if (typeof typ === typeof val) return val;
74+ return invalidValue(typ, val, key, parent);
75+ }
76+
77+ function transformUnion(typs: any[], val: any): any {
78+ // val must validate against one typ in typs
79+ const l = typs.length;
80+ for (let i = 0; i < l; i++) {
81+ const typ = typs[i];
82+ try {
83+ return transform(val, typ, getProps);
84+ } catch (_) {}
85+ }
86+ return invalidValue(typs, val, key, parent);
87+ }
88+
89+ function transformEnum(cases: string[], val: any): any {
90+ if (cases.indexOf(val) !== -1) return val;
91+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
92+ }
93+
94+ function transformArray(typ: any, val: any): any {
95+ // val must be an array with no invalid elements
96+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
97+ return val.map(el => transform(el, typ, getProps));
98+ }
99+
100+ function transformDate(val: any): any {
101+ if (val === null) {
102+ return null;
103+ }
104+ const d = new Date(val);
105+ if (isNaN(d.valueOf())) {
106+ return invalidValue(l("Date"), val, key, parent);
107+ }
108+ return d;
109+ }
110+
111+ function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
112+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
113+ return invalidValue(l(ref || "object"), val, key, parent);
114+ }
115+ const result: any = {};
116+ Object.getOwnPropertyNames(props).forEach(key => {
117+ const prop = props[key];
118+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
119+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
120+ });
121+ Object.getOwnPropertyNames(val).forEach(key => {
122+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
123+ result[key] = transform(val[key], additional, getProps, key, ref);
124+ }
125+ });
126+ return result;
127+ }
128+
129+ if (typ === "any") return val;
130+ if (typ === null) {
131+ if (val === null) return val;
132+ return invalidValue(typ, val, key, parent);
133+ }
134+ if (typ === false) return invalidValue(typ, val, key, parent);
135+ let ref: any = undefined;
136+ while (typeof typ === "object" && typ.ref !== undefined) {
137+ ref = typ.ref;
138+ typ = typeMap[typ.ref];
139+ }
140+ if (Array.isArray(typ)) return transformEnum(typ, val);
141+ if (typeof typ === "object") {
142+ return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
143+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
144+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
145+ : invalidValue(typ, val, key, parent);
146+ }
147+ // Numbers can be parsed by Date but shouldn't be.
148+ if (typ === Date && typeof val !== "number") return transformDate(val);
149+ return transformPrimitive(typ, val);
150+}
151+
152+function cast<T>(val: any, typ: any): T {
153+ return transform(val, typ, jsonToJSProps);
154+}
155+
156+function uncast<T>(val: T, typ: any): any {
157+ return transform(val, typ, jsToJSONProps);
158+}
159+
160+function l(typ: any) {
161+ return { literal: typ };
162+}
163+
164+function a(typ: any) {
165+ return { arrayItems: typ };
166+}
167+
168+function u(...typs: any[]) {
169+ return { unionMembers: typs };
170+}
171+
172+function o(props: any[], additional: any) {
173+ return { props, additional };
174+}
175+
176+function m(additional: any) {
177+ const props: any[] = [];
178+ return { props, additional };
179+}
180+
181+function r(name: string) {
182+ return { ref: name };
183+}
184+
185+const typeMap: any = {
186+ "TopLevel": o([
187+ { json: "animal", js: "animal", typ: u(undefined, u(r("Dog"), null)) },
188+ ], false),
189+ "Dog": o([
190+ { json: "discriminator", js: "discriminator", typ: "" },
191+ { json: "foo", js: "foo", typ: u(undefined, u(null, "")) },
192+ { json: "bar", js: "bar", typ: u(undefined, u(null, "")) },
193+ ], false),
194+};
No generated files match these filters.