Aschema-csharp-SystemTextJson/test/inputs/schema/named-class-union.schema/default/QuickType.cs+70 −0
| @@ -0,0 +1,70 @@ | ||
| 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("op", Required = Required.Always)] | |
| 29 | + public Foo Op { get; set; } | |
| 30 | + } | |
| 31 | + | |
| 32 | + public partial class Foo | |
| 33 | + { | |
| 34 | + [JsonProperty("foo", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 35 | + public string? FooFoo { get; set; } | |
| 36 | + | |
| 37 | + [JsonProperty("bar", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 38 | + public string? Bar { get; set; } | |
| 39 | + } | |
| 40 | + | |
| 41 | + public partial class TopLevel | |
| 42 | + { | |
| 43 | + public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings); | |
| 44 | + } | |
| 45 | + | |
| 46 | + public static partial class Serialize | |
| 47 | + { | |
| 48 | + public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings); | |
| 49 | + } | |
| 50 | + | |
| 51 | + internal static partial class Converter | |
| 52 | + { | |
| 53 | + public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings | |
| 54 | + { | |
| 55 | + MetadataPropertyHandling = MetadataPropertyHandling.Ignore, | |
| 56 | + DateParseHandling = DateParseHandling.None, | |
| 57 | + Converters = | |
| 58 | + { | |
| 59 | + new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal } | |
| 60 | + }, | |
| 61 | + }; | |
| 62 | + } | |
| 63 | +} | |
| 64 | +#pragma warning restore CS8618 | |
| 65 | +#pragma warning restore CS8601 | |
| 66 | +#pragma warning restore CS8602 | |
| 67 | +#pragma warning restore CS8603 | |
| 68 | +#pragma warning restore CS8604 | |
| 69 | +#pragma warning restore CS8625 | |
| 70 | +#pragma warning restore CS8765 |
Aschema-csharp/test/inputs/schema/named-class-union.schema/default/QuickType.cs+177 −0
| @@ -0,0 +1,177 @@ | ||
| 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 | + [JsonRequired] | |
| 26 | + [JsonPropertyName("op")] | |
| 27 | + public Foo Op { get; set; } | |
| 28 | + } | |
| 29 | + | |
| 30 | + public partial class Foo | |
| 31 | + { | |
| 32 | + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] | |
| 33 | + [JsonPropertyName("foo")] | |
| 34 | + public string? FooFoo { get; set; } | |
| 35 | + | |
| 36 | + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] | |
| 37 | + [JsonPropertyName("bar")] | |
| 38 | + public string? Bar { get; set; } | |
| 39 | + } | |
| 40 | + | |
| 41 | + public partial class TopLevel | |
| 42 | + { | |
| 43 | + public static TopLevel FromJson(string json) => JsonSerializer.Deserialize<TopLevel>(json, QuickType.Converter.Settings); | |
| 44 | + } | |
| 45 | + | |
| 46 | + public static partial class Serialize | |
| 47 | + { | |
| 48 | + public static string ToJson(this TopLevel self) => JsonSerializer.Serialize(self, QuickType.Converter.Settings); | |
| 49 | + } | |
| 50 | + | |
| 51 | + internal static partial class Converter | |
| 52 | + { | |
| 53 | + public static readonly JsonSerializerOptions Settings = new(JsonSerializerDefaults.General) | |
| 54 | + { | |
| 55 | + Converters = | |
| 56 | + { | |
| 57 | + new DateOnlyConverter(), | |
| 58 | + new TimeOnlyConverter(), | |
| 59 | + IsoDateTimeOffsetConverter.Singleton | |
| 60 | + }, | |
| 61 | + }; | |
| 62 | + } | |
| 63 | + | |
| 64 | + public class DateOnlyConverter : JsonConverter<DateOnly> | |
| 65 | + { | |
| 66 | + private readonly string serializationFormat; | |
| 67 | + public DateOnlyConverter() : this(null) { } | |
| 68 | + | |
| 69 | + public DateOnlyConverter(string? serializationFormat) | |
| 70 | + { | |
| 71 | + this.serializationFormat = serializationFormat ?? "yyyy-MM-dd"; | |
| 72 | + } | |
| 73 | + | |
| 74 | + public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
| 75 | + { | |
| 76 | + var value = reader.GetString(); | |
| 77 | + return DateOnly.Parse(value!); | |
| 78 | + } | |
| 79 | + | |
| 80 | + public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options) | |
| 81 | + => writer.WriteStringValue(value.ToString(serializationFormat)); | |
| 82 | + } | |
| 83 | + | |
| 84 | + public class TimeOnlyConverter : JsonConverter<TimeOnly> | |
| 85 | + { | |
| 86 | + private readonly string serializationFormat; | |
| 87 | + | |
| 88 | + public TimeOnlyConverter() : this(null) { } | |
| 89 | + | |
| 90 | + public TimeOnlyConverter(string? serializationFormat) | |
| 91 | + { | |
| 92 | + this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff"; | |
| 93 | + } | |
| 94 | + | |
| 95 | + public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
| 96 | + { | |
| 97 | + var value = reader.GetString(); | |
| 98 | + return TimeOnly.Parse(value!); | |
| 99 | + } | |
| 100 | + | |
| 101 | + public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options) | |
| 102 | + => writer.WriteStringValue(value.ToString(serializationFormat)); | |
| 103 | + } | |
| 104 | + | |
| 105 | + internal class IsoDateTimeOffsetConverter : JsonConverter<DateTimeOffset> | |
| 106 | + { | |
| 107 | + public override bool CanConvert(Type t) => t == typeof(DateTimeOffset); | |
| 108 | + | |
| 109 | + private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; | |
| 110 | + | |
| 111 | + private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind; | |
| 112 | + private string? _dateTimeFormat; | |
| 113 | + private CultureInfo? _culture; | |
| 114 | + | |
| 115 | + public DateTimeStyles DateTimeStyles | |
| 116 | + { | |
| 117 | + get => _dateTimeStyles; | |
| 118 | + set => _dateTimeStyles = value; | |
| 119 | + } | |
| 120 | + | |
| 121 | + public string? DateTimeFormat | |
| 122 | + { | |
| 123 | + get => _dateTimeFormat ?? string.Empty; | |
| 124 | + set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value; | |
| 125 | + } | |
| 126 | + | |
| 127 | + public CultureInfo Culture | |
| 128 | + { | |
| 129 | + get => _culture ?? CultureInfo.CurrentCulture; | |
| 130 | + set => _culture = value; | |
| 131 | + } | |
| 132 | + | |
| 133 | + public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options) | |
| 134 | + { | |
| 135 | + string text; | |
| 136 | + | |
| 137 | + | |
| 138 | + if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal | |
| 139 | + || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal) | |
| 140 | + { | |
| 141 | + value = value.ToUniversalTime(); | |
| 142 | + } | |
| 143 | + | |
| 144 | + text = value.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture); | |
| 145 | + | |
| 146 | + writer.WriteStringValue(text); | |
| 147 | + } | |
| 148 | + | |
| 149 | + public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
| 150 | + { | |
| 151 | + string? dateText = reader.GetString(); | |
| 152 | + | |
| 153 | + if (string.IsNullOrEmpty(dateText) == false) | |
| 154 | + { | |
| 155 | + if (!string.IsNullOrEmpty(_dateTimeFormat)) | |
| 156 | + { | |
| 157 | + return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles); | |
| 158 | + } | |
| 159 | + else | |
| 160 | + { | |
| 161 | + return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles); | |
| 162 | + } | |
| 163 | + } | |
| 164 | + else | |
| 165 | + { | |
| 166 | + return default(DateTimeOffset); | |
| 167 | + } | |
| 168 | + } | |
| 169 | + | |
| 170 | + | |
| 171 | + public static readonly IsoDateTimeOffsetConverter Singleton = new IsoDateTimeOffsetConverter(); | |
| 172 | + } | |
| 173 | +} | |
| 174 | +#pragma warning restore CS8618 | |
| 175 | +#pragma warning restore CS8601 | |
| 176 | +#pragma warning restore CS8602 | |
| 177 | +#pragma warning restore CS8603 |
Aschema-dart/test/inputs/schema/named-class-union.schema/default/TopLevel.dart+45 −0
| @@ -0,0 +1,45 @@ | ||
| 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 Foo op; | |
| 13 | + | |
| 14 | + TopLevel({ | |
| 15 | + required this.op, | |
| 16 | + }); | |
| 17 | + | |
| 18 | + factory TopLevel.fromJson(Map<String, dynamic> json) => TopLevel( | |
| 19 | + op: Foo.fromJson(json["op"]), | |
| 20 | + ); | |
| 21 | + | |
| 22 | + Map<String, dynamic> toJson() => { | |
| 23 | + "op": op.toJson(), | |
| 24 | + }; | |
| 25 | +} | |
| 26 | + | |
| 27 | +class Foo { | |
| 28 | + final String? foo; | |
| 29 | + final String? bar; | |
| 30 | + | |
| 31 | + Foo({ | |
| 32 | + this.foo, | |
| 33 | + this.bar, | |
| 34 | + }); | |
| 35 | + | |
| 36 | + factory Foo.fromJson(Map<String, dynamic> json) => Foo( | |
| 37 | + foo: json["foo"], | |
| 38 | + bar: json["bar"], | |
| 39 | + ); | |
| 40 | + | |
| 41 | + Map<String, dynamic> toJson() => { | |
| 42 | + "foo": foo, | |
| 43 | + "bar": bar, | |
| 44 | + }; | |
| 45 | +} |
Aschema-elixir/test/inputs/schema/named-class-union.schema/default/QuickType.ex+74 −0
| @@ -0,0 +1,74 @@ | ||
| 1 | +# This file was autogenerated using quicktype https://github.com/quicktype/quicktype | |
| 2 | +# | |
| 3 | +# Add Jason to your mix.exs | |
| 4 | +# | |
| 5 | +# Decode a JSON string: TopLevel.from_json(data) | |
| 6 | +# Encode into a JSON string: TopLevel.to_json(struct) | |
| 7 | + | |
| 8 | +defmodule Foo do | |
| 9 | + defstruct [:foo, :bar] | |
| 10 | + | |
| 11 | + @type t :: %__MODULE__{ | |
| 12 | + foo: String.t() | nil, | |
| 13 | + bar: String.t() | nil | |
| 14 | + } | |
| 15 | + | |
| 16 | + def from_map(m) do | |
| 17 | + %Foo{ | |
| 18 | + foo: m["foo"], | |
| 19 | + bar: m["bar"], | |
| 20 | + } | |
| 21 | + end | |
| 22 | + | |
| 23 | + def from_json(json) do | |
| 24 | + json | |
| 25 | + |> Jason.decode!() | |
| 26 | + |> from_map() | |
| 27 | + end | |
| 28 | + | |
| 29 | + def to_map(struct) do | |
| 30 | + %{ | |
| 31 | + "foo" => struct.foo, | |
| 32 | + "bar" => struct.bar, | |
| 33 | + } | |
| 34 | + end | |
| 35 | + | |
| 36 | + def to_json(struct) do | |
| 37 | + struct | |
| 38 | + |> to_map() | |
| 39 | + |> Jason.encode!() | |
| 40 | + end | |
| 41 | +end | |
| 42 | + | |
| 43 | +defmodule TopLevel do | |
| 44 | + @enforce_keys [:op] | |
| 45 | + defstruct [:op] | |
| 46 | + | |
| 47 | + @type t :: %__MODULE__{ | |
| 48 | + op: Foo.t() | |
| 49 | + } | |
| 50 | + | |
| 51 | + def from_map(m) do | |
| 52 | + %TopLevel{ | |
| 53 | + op: Foo.from_map(m["op"]), | |
| 54 | + } | |
| 55 | + end | |
| 56 | + | |
| 57 | + def from_json(json) do | |
| 58 | + json | |
| 59 | + |> Jason.decode!() | |
| 60 | + |> from_map() | |
| 61 | + end | |
| 62 | + | |
| 63 | + def to_map(struct) do | |
| 64 | + %{ | |
| 65 | + "op" => Foo.to_map(struct.op), | |
| 66 | + } | |
| 67 | + end | |
| 68 | + | |
| 69 | + def to_json(struct) do | |
| 70 | + struct | |
| 71 | + |> to_map() | |
| 72 | + |> Jason.encode!() | |
| 73 | + end | |
| 74 | +end |
Aschema-flow/test/inputs/schema/named-class-union.schema/default/TopLevel.js+197 −0
| @@ -0,0 +1,197 @@ | ||
| 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 | + op: Foo; | |
| 14 | +}; | |
| 15 | + | |
| 16 | +export type Foo = { | |
| 17 | + foo?: string; | |
| 18 | + bar?: string; | |
| 19 | +}; | |
| 20 | + | |
| 21 | +// Converts JSON strings to/from your types | |
| 22 | +// and asserts the results of JSON.parse at runtime | |
| 23 | +function toTopLevel(json: string): TopLevel { | |
| 24 | + return cast(JSON.parse(json), r("TopLevel")); | |
| 25 | +} | |
| 26 | + | |
| 27 | +function topLevelToJson(value: TopLevel): string { | |
| 28 | + return JSON.stringify(uncast(value, r("TopLevel")), null, 2); | |
| 29 | +} | |
| 30 | + | |
| 31 | +function invalidValue(typ: any, val: any, key: any, parent: any = '') { | |
| 32 | + const prettyTyp = prettyTypeName(typ); | |
| 33 | + const parentText = parent ? ` on ${parent}` : ''; | |
| 34 | + const keyText = key ? ` for key "${key}"` : ''; | |
| 35 | + throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`); | |
| 36 | +} | |
| 37 | + | |
| 38 | +function prettyTypeName(typ: any): string { | |
| 39 | + if (Array.isArray(typ)) { | |
| 40 | + if (typ.length === 2 && typ[0] === undefined) { | |
| 41 | + return `an optional ${prettyTypeName(typ[1])}`; | |
| 42 | + } else { | |
| 43 | + return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`; | |
| 44 | + } | |
| 45 | + } else if (typeof typ === "object" && typ.literal !== undefined) { | |
| 46 | + return typ.literal; | |
| 47 | + } else { | |
| 48 | + return typeof typ; | |
| 49 | + } | |
| 50 | +} | |
| 51 | + | |
| 52 | +function jsonToJSProps(typ: any): any { | |
| 53 | + if (typ.jsonToJS === undefined) { | |
| 54 | + const map: any = {}; | |
| 55 | + typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ }); | |
| 56 | + typ.jsonToJS = map; | |
| 57 | + } | |
| 58 | + return typ.jsonToJS; | |
| 59 | +} | |
| 60 | + | |
| 61 | +function jsToJSONProps(typ: any): any { | |
| 62 | + if (typ.jsToJSON === undefined) { | |
| 63 | + const map: any = {}; | |
| 64 | + typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ }); | |
| 65 | + typ.jsToJSON = map; | |
| 66 | + } | |
| 67 | + return typ.jsToJSON; | |
| 68 | +} | |
| 69 | + | |
| 70 | +function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any { | |
| 71 | + function transformPrimitive(typ: string, val: any): any { | |
| 72 | + if (typeof typ === typeof val) return val; | |
| 73 | + return invalidValue(typ, val, key, parent); | |
| 74 | + } | |
| 75 | + | |
| 76 | + function transformUnion(typs: any[], val: any): any { | |
| 77 | + // val must validate against one typ in typs | |
| 78 | + const l = typs.length; | |
| 79 | + for (let i = 0; i < l; i++) { | |
| 80 | + const typ = typs[i]; | |
| 81 | + try { | |
| 82 | + return transform(val, typ, getProps); | |
| 83 | + } catch (_) {} | |
| 84 | + } | |
| 85 | + return invalidValue(typs, val, key, parent); | |
| 86 | + } | |
| 87 | + | |
| 88 | + function transformEnum(cases: string[], val: any): any { | |
| 89 | + if (cases.indexOf(val) !== -1) return val; | |
| 90 | + return invalidValue(cases.map(a => { return l(a); }), val, key, parent); | |
| 91 | + } | |
| 92 | + | |
| 93 | + function transformArray(typ: any, val: any): any { | |
| 94 | + // val must be an array with no invalid elements | |
| 95 | + if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent); | |
| 96 | + return val.map(el => transform(el, typ, getProps)); | |
| 97 | + } | |
| 98 | + | |
| 99 | + function transformDate(val: any): any { | |
| 100 | + if (val === null) { | |
| 101 | + return null; | |
| 102 | + } | |
| 103 | + const d = new Date(val); | |
| 104 | + if (isNaN(d.valueOf())) { | |
| 105 | + return invalidValue(l("Date"), val, key, parent); | |
| 106 | + } | |
| 107 | + return d; | |
| 108 | + } | |
| 109 | + | |
| 110 | + function transformObject(props: { [k: string]: any }, additional: any, val: any): any { | |
| 111 | + if (val === null || typeof val !== "object" || Array.isArray(val)) { | |
| 112 | + return invalidValue(l(ref || "object"), val, key, parent); | |
| 113 | + } | |
| 114 | + const result: any = {}; | |
| 115 | + Object.getOwnPropertyNames(props).forEach(key => { | |
| 116 | + const prop = props[key]; | |
| 117 | + const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined; | |
| 118 | + result[prop.key] = transform(v, prop.typ, getProps, key, ref); | |
| 119 | + }); | |
| 120 | + Object.getOwnPropertyNames(val).forEach(key => { | |
| 121 | + if (!Object.prototype.hasOwnProperty.call(props, key)) { | |
| 122 | + result[key] = transform(val[key], additional, getProps, key, ref); | |
| 123 | + } | |
| 124 | + }); | |
| 125 | + return result; | |
| 126 | + } | |
| 127 | + | |
| 128 | + if (typ === "any") return val; | |
| 129 | + if (typ === null) { | |
| 130 | + if (val === null) return val; | |
| 131 | + return invalidValue(typ, val, key, parent); | |
| 132 | + } | |
| 133 | + if (typ === false) return invalidValue(typ, val, key, parent); | |
| 134 | + let ref: any = undefined; | |
| 135 | + while (typeof typ === "object" && typ.ref !== undefined) { | |
| 136 | + ref = typ.ref; | |
| 137 | + typ = typeMap[typ.ref]; | |
| 138 | + } | |
| 139 | + if (Array.isArray(typ)) return transformEnum(typ, val); | |
| 140 | + if (typeof typ === "object") { | |
| 141 | + return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val) | |
| 142 | + : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val) | |
| 143 | + : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val) | |
| 144 | + : invalidValue(typ, val, key, parent); | |
| 145 | + } | |
| 146 | + // Numbers can be parsed by Date but shouldn't be. | |
| 147 | + if (typ === Date && typeof val !== "number") return transformDate(val); | |
| 148 | + return transformPrimitive(typ, val); | |
| 149 | +} | |
| 150 | + | |
| 151 | +function cast<T>(val: any, typ: any): T { | |
| 152 | + return transform(val, typ, jsonToJSProps); | |
| 153 | +} | |
| 154 | + | |
| 155 | +function uncast<T>(val: T, typ: any): any { | |
| 156 | + return transform(val, typ, jsToJSONProps); | |
| 157 | +} | |
| 158 | + | |
| 159 | +function l(typ: any) { | |
| 160 | + return { literal: typ }; | |
| 161 | +} | |
| 162 | + | |
| 163 | +function a(typ: any) { | |
| 164 | + return { arrayItems: typ }; | |
| 165 | +} | |
| 166 | + | |
| 167 | +function u(...typs: any[]) { | |
| 168 | + return { unionMembers: typs }; | |
| 169 | +} | |
| 170 | + | |
| 171 | +function o(props: any[], additional: any) { | |
| 172 | + return { props, additional }; | |
| 173 | +} | |
| 174 | + | |
| 175 | +function m(additional: any) { | |
| 176 | + const props: any[] = []; | |
| 177 | + return { props, additional }; | |
| 178 | +} | |
| 179 | + | |
| 180 | +function r(name: string) { | |
| 181 | + return { ref: name }; | |
| 182 | +} | |
| 183 | + | |
| 184 | +const typeMap: any = { | |
| 185 | + "TopLevel": o([ | |
| 186 | + { json: "op", js: "op", typ: r("Foo") }, | |
| 187 | + ], false), | |
| 188 | + "Foo": o([ | |
| 189 | + { json: "foo", js: "foo", typ: u(undefined, "") }, | |
| 190 | + { json: "bar", js: "bar", typ: u(undefined, "") }, | |
| 191 | + ], false), | |
| 192 | +}; | |
| 193 | + | |
| 194 | +module.exports = { | |
| 195 | + "topLevelToJson": topLevelToJson, | |
| 196 | + "toTopLevel": toTopLevel, | |
| 197 | +}; |
Aschema-golang/test/inputs/schema/named-class-union.schema/default/quicktype.go+28 −0
| @@ -0,0 +1,28 @@ | ||
| 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 | + Op Foo `json:"op"` | |
| 23 | +} | |
| 24 | + | |
| 25 | +type Foo struct { | |
| 26 | + Foo *string `json:"foo,omitempty"` | |
| 27 | + Bar *string `json:"bar,omitempty"` | |
| 28 | +} |
Aschema-java-datetime-legacy/test/inputs/schema/named-class-union.schema/default/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-datetime-legacy/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Foo.java+18 −0
| @@ -0,0 +1,18 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | + | |
| 5 | +public class Foo { | |
| 6 | + private String foo; | |
| 7 | + private String bar; | |
| 8 | + | |
| 9 | + @JsonProperty("foo") | |
| 10 | + public String getFoo() { return foo; } | |
| 11 | + @JsonProperty("foo") | |
| 12 | + public void setFoo(String value) { this.foo = value; } | |
| 13 | + | |
| 14 | + @JsonProperty("bar") | |
| 15 | + public String getBar() { return bar; } | |
| 16 | + @JsonProperty("bar") | |
| 17 | + public void setBar(String value) { this.bar = value; } | |
| 18 | +} |
Aschema-java-datetime-legacy/test/inputs/schema/named-class-union.schema/default/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 Foo op; | |
| 7 | + | |
| 8 | + @JsonProperty("op") | |
| 9 | + public Foo getOp() { return op; } | |
| 10 | + @JsonProperty("op") | |
| 11 | + public void setOp(Foo value) { this.op = value; } | |
| 12 | +} |
Aschema-java-lombok/test/inputs/schema/named-class-union.schema/default/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-lombok/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Foo.java+18 −0
| @@ -0,0 +1,18 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | + | |
| 5 | +public class Foo { | |
| 6 | + private String foo; | |
| 7 | + private String bar; | |
| 8 | + | |
| 9 | + @JsonProperty("foo") | |
| 10 | + public String getFoo() { return foo; } | |
| 11 | + @JsonProperty("foo") | |
| 12 | + public void setFoo(String value) { this.foo = value; } | |
| 13 | + | |
| 14 | + @JsonProperty("bar") | |
| 15 | + public String getBar() { return bar; } | |
| 16 | + @JsonProperty("bar") | |
| 17 | + public void setBar(String value) { this.bar = value; } | |
| 18 | +} |
Aschema-java-lombok/test/inputs/schema/named-class-union.schema/default/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 Foo op; | |
| 7 | + | |
| 8 | + @JsonProperty("op") | |
| 9 | + public Foo getOp() { return op; } | |
| 10 | + @JsonProperty("op") | |
| 11 | + public void setOp(Foo value) { this.op = value; } | |
| 12 | +} |
Aschema-java/test/inputs/schema/named-class-union.schema/default/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/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Foo.java+18 −0
| @@ -0,0 +1,18 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | + | |
| 5 | +public class Foo { | |
| 6 | + private String foo; | |
| 7 | + private String bar; | |
| 8 | + | |
| 9 | + @JsonProperty("foo") | |
| 10 | + public String getFoo() { return foo; } | |
| 11 | + @JsonProperty("foo") | |
| 12 | + public void setFoo(String value) { this.foo = value; } | |
| 13 | + | |
| 14 | + @JsonProperty("bar") | |
| 15 | + public String getBar() { return bar; } | |
| 16 | + @JsonProperty("bar") | |
| 17 | + public void setBar(String value) { this.bar = value; } | |
| 18 | +} |
Aschema-java/test/inputs/schema/named-class-union.schema/default/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 Foo op; | |
| 7 | + | |
| 8 | + @JsonProperty("op") | |
| 9 | + public Foo getOp() { return op; } | |
| 10 | + @JsonProperty("op") | |
| 11 | + public void setOp(Foo value) { this.op = value; } | |
| 12 | +} |
Aschema-javascript/test/inputs/schema/named-class-union.schema/default/TopLevel.js+186 −0
| @@ -0,0 +1,186 @@ | ||
| 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: "op", js: "op", typ: r("Foo") }, | |
| 176 | + ], false), | |
| 177 | + "Foo": o([ | |
| 178 | + { json: "foo", js: "foo", typ: u(undefined, "") }, | |
| 179 | + { json: "bar", js: "bar", typ: u(undefined, "") }, | |
| 180 | + ], false), | |
| 181 | +}; | |
| 182 | + | |
| 183 | +module.exports = { | |
| 184 | + "topLevelToJson": topLevelToJson, | |
| 185 | + "toTopLevel": toTopLevel, | |
| 186 | +}; |
Aschema-kotlinx/test/inputs/schema/named-class-union.schema/default/TopLevel.kt+22 −0
| @@ -0,0 +1,22 @@ | ||
| 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 op: Foo | |
| 16 | +) | |
| 17 | + | |
| 18 | +@Serializable | |
| 19 | +data class Foo ( | |
| 20 | + val foo: String? = null, | |
| 21 | + val bar: String? = null | |
| 22 | +) |
Aschema-php/test/inputs/schema/named-class-union.schema/default/TopLevel.php+273 −0
| @@ -0,0 +1,273 @@ | ||
| 1 | +<?php | |
| 2 | +declare(strict_types=1); | |
| 3 | + | |
| 4 | +// This is an autogenerated file:TopLevel | |
| 5 | + | |
| 6 | +class TopLevel { | |
| 7 | + private Foo $op; // json:op Required | |
| 8 | + | |
| 9 | + /** | |
| 10 | + * @param Foo $op | |
| 11 | + */ | |
| 12 | + public function __construct(Foo $op) { | |
| 13 | + $this->op = $op; | |
| 14 | + } | |
| 15 | + | |
| 16 | + /** | |
| 17 | + * @param stdClass $value | |
| 18 | + * @throws Exception | |
| 19 | + * @return Foo | |
| 20 | + */ | |
| 21 | + public static function fromOp(stdClass $value): Foo { | |
| 22 | + return Foo::from($value); /*class*/ | |
| 23 | + } | |
| 24 | + | |
| 25 | + /** | |
| 26 | + * @throws Exception | |
| 27 | + * @return stdClass | |
| 28 | + */ | |
| 29 | + public function toOp(): stdClass { | |
| 30 | + if (TopLevel::validateOp($this->op)) { | |
| 31 | + return $this->op->to(); /*class*/ | |
| 32 | + } | |
| 33 | + throw new Exception('never get to this TopLevel::op'); | |
| 34 | + } | |
| 35 | + | |
| 36 | + /** | |
| 37 | + * @param Foo | |
| 38 | + * @return bool | |
| 39 | + * @throws Exception | |
| 40 | + */ | |
| 41 | + public static function validateOp(Foo $value): bool { | |
| 42 | + $value->validate(); | |
| 43 | + return true; | |
| 44 | + } | |
| 45 | + | |
| 46 | + /** | |
| 47 | + * @throws Exception | |
| 48 | + * @return Foo | |
| 49 | + */ | |
| 50 | + public function getOp(): Foo { | |
| 51 | + if (TopLevel::validateOp($this->op)) { | |
| 52 | + return $this->op; | |
| 53 | + } | |
| 54 | + throw new Exception('never get to getOp TopLevel::op'); | |
| 55 | + } | |
| 56 | + | |
| 57 | + /** | |
| 58 | + * @return Foo | |
| 59 | + */ | |
| 60 | + public static function sampleOp(): Foo { | |
| 61 | + return Foo::sample(); /*31:op*/ | |
| 62 | + } | |
| 63 | + | |
| 64 | + /** | |
| 65 | + * @throws Exception | |
| 66 | + * @return bool | |
| 67 | + */ | |
| 68 | + public function validate(): bool { | |
| 69 | + return TopLevel::validateOp($this->op); | |
| 70 | + } | |
| 71 | + | |
| 72 | + /** | |
| 73 | + * @return stdClass | |
| 74 | + * @throws Exception | |
| 75 | + */ | |
| 76 | + public function to(): stdClass { | |
| 77 | + $out = new stdClass(); | |
| 78 | + $out->{'op'} = $this->toOp(); | |
| 79 | + return $out; | |
| 80 | + } | |
| 81 | + | |
| 82 | + /** | |
| 83 | + * @param stdClass $obj | |
| 84 | + * @return TopLevel | |
| 85 | + * @throws Exception | |
| 86 | + */ | |
| 87 | + public static function from(stdClass $obj): TopLevel { | |
| 88 | + return new TopLevel( | |
| 89 | + TopLevel::fromOp($obj->{'op'}) | |
| 90 | + ); | |
| 91 | + } | |
| 92 | + | |
| 93 | + /** | |
| 94 | + * @return TopLevel | |
| 95 | + */ | |
| 96 | + public static function sample(): TopLevel { | |
| 97 | + return new TopLevel( | |
| 98 | + TopLevel::sampleOp() | |
| 99 | + ); | |
| 100 | + } | |
| 101 | +} | |
| 102 | + | |
| 103 | +// This is an autogenerated file:Foo | |
| 104 | + | |
| 105 | +class Foo { | |
| 106 | + private ?string $foo; // json:foo Optional | |
| 107 | + private ?string $bar; // json:bar Optional | |
| 108 | + | |
| 109 | + /** | |
| 110 | + * @param string|null $foo | |
| 111 | + * @param string|null $bar | |
| 112 | + */ | |
| 113 | + public function __construct(?string $foo, ?string $bar) { | |
| 114 | + $this->foo = $foo; | |
| 115 | + $this->bar = $bar; | |
| 116 | + } | |
| 117 | + | |
| 118 | + /** | |
| 119 | + * @param ?string $value | |
| 120 | + * @throws Exception | |
| 121 | + * @return ?string | |
| 122 | + */ | |
| 123 | + public static function fromFoo(?string $value): ?string { | |
| 124 | + if (!is_null($value)) { | |
| 125 | + return $value; /*string*/ | |
| 126 | + } else { | |
| 127 | + return null; | |
| 128 | + } | |
| 129 | + } | |
| 130 | + | |
| 131 | + /** | |
| 132 | + * @throws Exception | |
| 133 | + * @return ?string | |
| 134 | + */ | |
| 135 | + public function toFoo(): ?string { | |
| 136 | + if (Foo::validateFoo($this->foo)) { | |
| 137 | + if (!is_null($this->foo)) { | |
| 138 | + return $this->foo; /*string*/ | |
| 139 | + } else { | |
| 140 | + return null; | |
| 141 | + } | |
| 142 | + } | |
| 143 | + throw new Exception('never get to this Foo::foo'); | |
| 144 | + } | |
| 145 | + | |
| 146 | + /** | |
| 147 | + * @param string|null | |
| 148 | + * @return bool | |
| 149 | + * @throws Exception | |
| 150 | + */ | |
| 151 | + public static function validateFoo(?string $value): bool { | |
| 152 | + if (!is_null($value)) { | |
| 153 | + } | |
| 154 | + return true; | |
| 155 | + } | |
| 156 | + | |
| 157 | + /** | |
| 158 | + * @throws Exception | |
| 159 | + * @return ?string | |
| 160 | + */ | |
| 161 | + public function getFoo(): ?string { | |
| 162 | + if (Foo::validateFoo($this->foo)) { | |
| 163 | + return $this->foo; | |
| 164 | + } | |
| 165 | + throw new Exception('never get to getFoo Foo::foo'); | |
| 166 | + } | |
| 167 | + | |
| 168 | + /** | |
| 169 | + * @return ?string | |
| 170 | + */ | |
| 171 | + public static function sampleFoo(): ?string { | |
| 172 | + return 'Foo::foo::31'; /*31:foo*/ | |
| 173 | + } | |
| 174 | + | |
| 175 | + /** | |
| 176 | + * @param ?string $value | |
| 177 | + * @throws Exception | |
| 178 | + * @return ?string | |
| 179 | + */ | |
| 180 | + public static function fromBar(?string $value): ?string { | |
| 181 | + if (!is_null($value)) { | |
| 182 | + return $value; /*string*/ | |
| 183 | + } else { | |
| 184 | + return null; | |
| 185 | + } | |
| 186 | + } | |
| 187 | + | |
| 188 | + /** | |
| 189 | + * @throws Exception | |
| 190 | + * @return ?string | |
| 191 | + */ | |
| 192 | + public function toBar(): ?string { | |
| 193 | + if (Foo::validateBar($this->bar)) { | |
| 194 | + if (!is_null($this->bar)) { | |
| 195 | + return $this->bar; /*string*/ | |
| 196 | + } else { | |
| 197 | + return null; | |
| 198 | + } | |
| 199 | + } | |
| 200 | + throw new Exception('never get to this Foo::bar'); | |
| 201 | + } | |
| 202 | + | |
| 203 | + /** | |
| 204 | + * @param string|null | |
| 205 | + * @return bool | |
| 206 | + * @throws Exception | |
| 207 | + */ | |
| 208 | + public static function validateBar(?string $value): bool { | |
| 209 | + if (!is_null($value)) { | |
| 210 | + } | |
| 211 | + return true; | |
| 212 | + } | |
| 213 | + | |
| 214 | + /** | |
| 215 | + * @throws Exception | |
| 216 | + * @return ?string | |
| 217 | + */ | |
| 218 | + public function getBar(): ?string { | |
| 219 | + if (Foo::validateBar($this->bar)) { | |
| 220 | + return $this->bar; | |
| 221 | + } | |
| 222 | + throw new Exception('never get to getBar Foo::bar'); | |
| 223 | + } | |
| 224 | + | |
| 225 | + /** | |
| 226 | + * @return ?string | |
| 227 | + */ | |
| 228 | + public static function sampleBar(): ?string { | |
| 229 | + return 'Foo::bar::32'; /*32:bar*/ | |
| 230 | + } | |
| 231 | + | |
| 232 | + /** | |
| 233 | + * @throws Exception | |
| 234 | + * @return bool | |
| 235 | + */ | |
| 236 | + public function validate(): bool { | |
| 237 | + return Foo::validateFoo($this->foo) | |
| 238 | + || Foo::validateBar($this->bar); | |
| 239 | + } | |
| 240 | + | |
| 241 | + /** | |
| 242 | + * @return stdClass | |
| 243 | + * @throws Exception | |
| 244 | + */ | |
| 245 | + public function to(): stdClass { | |
| 246 | + $out = new stdClass(); | |
| 247 | + $out->{'foo'} = $this->toFoo(); | |
| 248 | + $out->{'bar'} = $this->toBar(); | |
| 249 | + return $out; | |
| 250 | + } | |
| 251 | + | |
| 252 | + /** | |
| 253 | + * @param stdClass $obj | |
| 254 | + * @return Foo | |
| 255 | + * @throws Exception | |
| 256 | + */ | |
| 257 | + public static function from(stdClass $obj): Foo { | |
| 258 | + return new Foo( | |
| 259 | + Foo::fromFoo($obj->{'foo'}) | |
| 260 | + ,Foo::fromBar($obj->{'bar'}) | |
| 261 | + ); | |
| 262 | + } | |
| 263 | + | |
| 264 | + /** | |
| 265 | + * @return Foo | |
| 266 | + */ | |
| 267 | + public static function sample(): Foo { | |
| 268 | + return new Foo( | |
| 269 | + Foo::sampleFoo() | |
| 270 | + ,Foo::sampleBar() | |
| 271 | + ); | |
| 272 | + } | |
| 273 | +} |
Aschema-pike/test/inputs/schema/named-class-union.schema/default/TopLevel.pmod+56 −0
| @@ -0,0 +1,56 @@ | ||
| 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 | + Foo op; // json: "op" | |
| 17 | + | |
| 18 | + string encode_json() { | |
| 19 | + mapping(string:mixed) json = ([ | |
| 20 | + "op" : op, | |
| 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.op = json["op"]; | |
| 31 | + | |
| 32 | + return retval; | |
| 33 | +} | |
| 34 | + | |
| 35 | +class Foo { | |
| 36 | + mixed|string foo; // json: "foo" | |
| 37 | + mixed|string bar; // json: "bar" | |
| 38 | + | |
| 39 | + string encode_json() { | |
| 40 | + mapping(string:mixed) json = ([ | |
| 41 | + "foo" : foo, | |
| 42 | + "bar" : bar, | |
| 43 | + ]); | |
| 44 | + | |
| 45 | + return Standards.JSON.encode(json); | |
| 46 | + } | |
| 47 | +} | |
| 48 | + | |
| 49 | +Foo Foo_from_JSON(mixed json) { | |
| 50 | + Foo retval = Foo(); | |
| 51 | + | |
| 52 | + retval.foo = json["foo"]; | |
| 53 | + retval.bar = json["bar"]; | |
| 54 | + | |
| 55 | + return retval; | |
| 56 | +} |
Aschema-python/test/inputs/schema/named-class-union.schema/default/quicktype.py+80 −0
| @@ -0,0 +1,80 @@ | ||
| 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_union(fs, x): | |
| 14 | + for f in fs: | |
| 15 | + try: | |
| 16 | + return f(x) | |
| 17 | + except: | |
| 18 | + pass | |
| 19 | + assert False | |
| 20 | + | |
| 21 | + | |
| 22 | +def to_class(c: Type[T], x: Any) -> dict: | |
| 23 | + assert isinstance(x, c) | |
| 24 | + return cast(Any, x).to_dict() | |
| 25 | + | |
| 26 | + | |
| 27 | +@dataclass | |
| 28 | +class Foo: | |
| 29 | + foo: str | |
| 30 | + | |
| 31 | + @staticmethod | |
| 32 | + def from_dict(obj: Any) -> 'Foo': | |
| 33 | + assert isinstance(obj, dict) | |
| 34 | + foo = from_str(obj.get("foo")) | |
| 35 | + return Foo(foo) | |
| 36 | + | |
| 37 | + def to_dict(self) -> dict: | |
| 38 | + result: dict = {} | |
| 39 | + result["foo"] = from_str(self.foo) | |
| 40 | + return result | |
| 41 | + | |
| 42 | + | |
| 43 | +@dataclass | |
| 44 | +class Bar: | |
| 45 | + bar: str | |
| 46 | + | |
| 47 | + @staticmethod | |
| 48 | + def from_dict(obj: Any) -> 'Bar': | |
| 49 | + assert isinstance(obj, dict) | |
| 50 | + bar = from_str(obj.get("bar")) | |
| 51 | + return Bar(bar) | |
| 52 | + | |
| 53 | + def to_dict(self) -> dict: | |
| 54 | + result: dict = {} | |
| 55 | + result["bar"] = from_str(self.bar) | |
| 56 | + return result | |
| 57 | + | |
| 58 | + | |
| 59 | +@dataclass | |
| 60 | +class TopLevel: | |
| 61 | + op: Foo | Bar | |
| 62 | + | |
| 63 | + @staticmethod | |
| 64 | + def from_dict(obj: Any) -> 'TopLevel': | |
| 65 | + assert isinstance(obj, dict) | |
| 66 | + op = from_union([Foo.from_dict, Bar.from_dict], obj.get("op")) | |
| 67 | + return TopLevel(op) | |
| 68 | + | |
| 69 | + def to_dict(self) -> dict: | |
| 70 | + result: dict = {} | |
| 71 | + result["op"] = from_union([lambda x: to_class(Foo, x), lambda x: to_class(Bar, x)], self.op) | |
| 72 | + return result | |
| 73 | + | |
| 74 | + | |
| 75 | +def top_level_from_dict(s: Any) -> TopLevel: | |
| 76 | + return TopLevel.from_dict(s) | |
| 77 | + | |
| 78 | + | |
| 79 | +def top_level_to_dict(x: TopLevel) -> Any: | |
| 80 | + return to_class(TopLevel, x) |
Mschema-python/test/inputs/schema/vega-lite.schema/default/quicktype.py+51 −124
| @@ -5332,7 +5332,7 @@ class FacetFieldDef: | ||
| 5332 | 5332 | |
| 5333 | 5333 | |
| 5334 | 5334 | @dataclass |
| 5335 | -class FieldDef: | |
| 5335 | +class FieldDefElement: | |
| 5336 | 5336 | """Definition object for a data field, its type and transformation of an encoding channel.""" |
| 5337 | 5337 | |
| 5338 | 5338 | type: ConditionalPredicateValueDefType |
| @@ -5374,14 +5374,14 @@ class FieldDef: | ||
| 5374 | 5374 | """ |
| 5375 | 5375 | |
| 5376 | 5376 | @staticmethod |
| 5377 | - def from_dict(obj: Any) -> 'FieldDef': | |
| 5377 | + def from_dict(obj: Any) -> 'FieldDefElement': | |
| 5378 | 5378 | assert isinstance(obj, dict) |
| 5379 | 5379 | type = ConditionalPredicateValueDefType(obj.get("type")) |
| 5380 | 5380 | aggregate = from_union([AggregateOp, from_none], obj.get("aggregate")) |
| 5381 | 5381 | bin = from_union([from_bool, BinParams.from_dict, from_none], obj.get("bin")) |
| 5382 | 5382 | field = from_union([RepeatRef.from_dict, from_str, from_none], obj.get("field")) |
| 5383 | 5383 | time_unit = from_union([TimeUnit, from_none], obj.get("timeUnit")) |
| 5384 | - return FieldDef(type, aggregate, bin, field, time_unit) | |
| 5384 | + return FieldDefElement(type, aggregate, bin, field, time_unit) | |
| 5385 | 5385 | |
| 5386 | 5386 | def to_dict(self) -> dict: |
| 5387 | 5387 | result: dict = {} |
| @@ -6065,12 +6065,12 @@ class Axis: | ||
| 6065 | 6065 | |
| 6066 | 6066 | |
| 6067 | 6067 | @dataclass |
| 6068 | -class XClass: | |
| 6069 | - """X coordinates of the marks, or width of horizontal `"bar"` and `"area"`. | |
| 6070 | - | |
| 6071 | - Y coordinates of the marks, or height of vertical `"bar"` and `"area"`. | |
| 6072 | - | |
| 6073 | - Definition object for a constant value of an encoding channel. | |
| 6068 | +class PositionFieldDef: | |
| 6069 | + type: ConditionalPredicateValueDefType | |
| 6070 | + """The encoded field's type of measurement (`"quantitative"`, `"temporal"`, `"ordinal"`, or | |
| 6071 | + `"nominal"`). | |
| 6072 | + It can also be a geo type (`"latitude"`, `"longitude"`, and `"geojson"`) when a | |
| 6073 | + [geographic projection](projection.html) is applied. | |
| 6074 | 6074 | """ |
| 6075 | 6075 | aggregate: AggregateOp | None = None |
| 6076 | 6076 | """Aggregation function for the field |
| @@ -6146,20 +6146,11 @@ class XClass: | ||
| 6146 | 6146 | |
| 6147 | 6147 | __Default value:__ `undefined` (None) |
| 6148 | 6148 | """ |
| 6149 | - type: ConditionalPredicateValueDefType | None = None | |
| 6150 | - """The encoded field's type of measurement (`"quantitative"`, `"temporal"`, `"ordinal"`, or | |
| 6151 | - `"nominal"`). | |
| 6152 | - It can also be a geo type (`"latitude"`, `"longitude"`, and `"geojson"`) when a | |
| 6153 | - [geographic projection](projection.html) is applied. | |
| 6154 | - """ | |
| 6155 | - value: float | bool | str | None = None | |
| 6156 | - """A constant value in visual domain (e.g., `"red"` / "#0099ff" for color, values between | |
| 6157 | - `0` to `1` for opacity). | |
| 6158 | - """ | |
| 6159 | 6149 | |
| 6160 | 6150 | @staticmethod |
| 6161 | - def from_dict(obj: Any) -> 'XClass': | |
| 6151 | + def from_dict(obj: Any) -> 'PositionFieldDef': | |
| 6162 | 6152 | assert isinstance(obj, dict) |
| 6153 | + type = ConditionalPredicateValueDefType(obj.get("type")) | |
| 6163 | 6154 | aggregate = from_union([AggregateOp, from_none], obj.get("aggregate")) |
| 6164 | 6155 | axis = from_union([Axis.from_dict, from_none], obj.get("axis")) |
| 6165 | 6156 | bin = from_union([from_bool, BinParams.from_dict, from_none], obj.get("bin")) |
| @@ -6168,12 +6159,11 @@ class XClass: | ||
| 6168 | 6159 | sort = from_union([from_none, SortField.from_dict, SortEnum], obj.get("sort")) |
| 6169 | 6160 | stack = from_union([StackOffset, from_none], obj.get("stack")) |
| 6170 | 6161 | time_unit = from_union([TimeUnit, from_none], obj.get("timeUnit")) |
| 6171 | - type = from_union([ConditionalPredicateValueDefType, from_none], obj.get("type")) | |
| 6172 | - value = from_union([from_float, from_bool, from_str, from_none], obj.get("value")) | |
| 6173 | - return XClass(aggregate, axis, bin, field, scale, sort, stack, time_unit, type, value) | |
| 6162 | + return PositionFieldDef(type, aggregate, axis, bin, field, scale, sort, stack, time_unit) | |
| 6174 | 6163 | |
| 6175 | 6164 | def to_dict(self) -> dict: |
| 6176 | 6165 | result: dict = {} |
| 6166 | + result["type"] = to_enum(ConditionalPredicateValueDefType, self.type) | |
| 6177 | 6167 | if self.aggregate is not None: |
| 6178 | 6168 | result["aggregate"] = from_union([lambda x: to_enum(AggregateOp, x), from_none], self.aggregate) |
| 6179 | 6169 | if self.axis is not None: |
| @@ -6190,90 +6180,27 @@ class XClass: | ||
| 6190 | 6180 | result["stack"] = from_union([lambda x: to_enum(StackOffset, x), from_none], self.stack) |
| 6191 | 6181 | if self.time_unit is not None: |
| 6192 | 6182 | result["timeUnit"] = from_union([lambda x: to_enum(TimeUnit, x), from_none], self.time_unit) |
| 6193 | - if self.type is not None: | |
| 6194 | - result["type"] = from_union([lambda x: to_enum(ConditionalPredicateValueDefType, x), from_none], self.type) | |
| 6195 | - if self.value is not None: | |
| 6196 | - result["value"] = from_union([to_float, from_bool, from_str, from_none], self.value) | |
| 6197 | 6183 | return result |
| 6198 | 6184 | |
| 6199 | 6185 | |
| 6200 | 6186 | @dataclass |
| 6201 | -class X2Class: | |
| 6202 | - """X2 coordinates for ranged `"area"`, `"bar"`, `"rect"`, and `"rule"`. | |
| 6203 | - | |
| 6204 | - Y2 coordinates for ranged `"area"`, `"bar"`, `"rect"`, and `"rule"`. | |
| 6205 | - | |
| 6206 | - Definition object for a data field, its type and transformation of an encoding channel. | |
| 6207 | - | |
| 6208 | - Definition object for a constant value of an encoding channel. | |
| 6209 | - """ | |
| 6210 | - aggregate: AggregateOp | None = None | |
| 6211 | - """Aggregation function for the field | |
| 6212 | - (e.g., `mean`, `sum`, `median`, `min`, `max`, `count`). | |
| 6213 | - | |
| 6214 | - __Default value:__ `undefined` (None) | |
| 6215 | - """ | |
| 6216 | - bin: bool | BinParams | None = None | |
| 6217 | - """A flag for binning a `quantitative` field, or [an object defining binning | |
| 6218 | - parameters](bin.html#params). | |
| 6219 | - If `true`, default [binning parameters](bin.html) will be applied. | |
| 6220 | - | |
| 6221 | - __Default value:__ `false` | |
| 6222 | - """ | |
| 6223 | - field: RepeatRef | str | None = None | |
| 6224 | - """__Required.__ A string defining the name of the field from which to pull a data value | |
| 6225 | - or an object defining iterated values from the [`repeat`](repeat.html) operator. | |
| 6226 | - | |
| 6227 | - __Note:__ Dots (`.`) and brackets (`[` and `]`) can be used to access nested objects | |
| 6228 | - (e.g., `"field": "foo.bar"` and `"field": "foo['bar']"`). | |
| 6229 | - If field names contain dots or brackets but are not nested, you can use `\\\\` to escape | |
| 6230 | - dots and brackets (e.g., `"a\\\\.b"` and `"a\\\\[0\\\\]"`). | |
| 6231 | - See more details about escaping in the [field documentation](field.html). | |
| 6232 | - | |
| 6233 | - __Note:__ `field` is not required if `aggregate` is `count`. | |
| 6234 | - """ | |
| 6235 | - time_unit: TimeUnit | None = None | |
| 6236 | - """Time unit (e.g., `year`, `yearmonth`, `month`, `hours`) for a temporal field. | |
| 6237 | - or [a temporal field that gets casted as ordinal](type.html#cast). | |
| 6238 | - | |
| 6239 | - __Default value:__ `undefined` (None) | |
| 6240 | - """ | |
| 6241 | - type: ConditionalPredicateValueDefType | None = None | |
| 6242 | - """The encoded field's type of measurement (`"quantitative"`, `"temporal"`, `"ordinal"`, or | |
| 6243 | - `"nominal"`). | |
| 6244 | - It can also be a geo type (`"latitude"`, `"longitude"`, and `"geojson"`) when a | |
| 6245 | - [geographic projection](projection.html) is applied. | |
| 6246 | - """ | |
| 6247 | - value: float | bool | str | None = None | |
| 6187 | +class ValueDef: | |
| 6188 | + """Definition object for a constant value of an encoding channel.""" | |
| 6189 | + | |
| 6190 | + value: float | bool | str | |
| 6248 | 6191 | """A constant value in visual domain (e.g., `"red"` / "#0099ff" for color, values between |
| 6249 | 6192 | `0` to `1` for opacity). |
| 6250 | 6193 | """ |
| 6251 | 6194 | |
| 6252 | 6195 | @staticmethod |
| 6253 | - def from_dict(obj: Any) -> 'X2Class': | |
| 6196 | + def from_dict(obj: Any) -> 'ValueDef': | |
| 6254 | 6197 | assert isinstance(obj, dict) |
| 6255 | - aggregate = from_union([AggregateOp, from_none], obj.get("aggregate")) | |
| 6256 | - bin = from_union([from_bool, BinParams.from_dict, from_none], obj.get("bin")) | |
| 6257 | - field = from_union([RepeatRef.from_dict, from_str, from_none], obj.get("field")) | |
| 6258 | - time_unit = from_union([TimeUnit, from_none], obj.get("timeUnit")) | |
| 6259 | - type = from_union([ConditionalPredicateValueDefType, from_none], obj.get("type")) | |
| 6260 | - value = from_union([from_float, from_bool, from_str, from_none], obj.get("value")) | |
| 6261 | - return X2Class(aggregate, bin, field, time_unit, type, value) | |
| 6198 | + value = from_union([from_float, from_bool, from_str], obj.get("value")) | |
| 6199 | + return ValueDef(value) | |
| 6262 | 6200 | |
| 6263 | 6201 | def to_dict(self) -> dict: |
| 6264 | 6202 | result: dict = {} |
| 6265 | - if self.aggregate is not None: | |
| 6266 | - result["aggregate"] = from_union([lambda x: to_enum(AggregateOp, x), from_none], self.aggregate) | |
| 6267 | - if self.bin is not None: | |
| 6268 | - result["bin"] = from_union([from_bool, lambda x: to_class(BinParams, x), from_none], self.bin) | |
| 6269 | - if self.field is not None: | |
| 6270 | - result["field"] = from_union([lambda x: to_class(RepeatRef, x), from_str, from_none], self.field) | |
| 6271 | - if self.time_unit is not None: | |
| 6272 | - result["timeUnit"] = from_union([lambda x: to_enum(TimeUnit, x), from_none], self.time_unit) | |
| 6273 | - if self.type is not None: | |
| 6274 | - result["type"] = from_union([lambda x: to_enum(ConditionalPredicateValueDefType, x), from_none], self.type) | |
| 6275 | - if self.value is not None: | |
| 6276 | - result["value"] = from_union([to_float, from_bool, from_str, from_none], self.value) | |
| 6203 | + result["value"] = from_union([to_float, from_bool, from_str], self.value) | |
| 6277 | 6204 | return result |
| 6278 | 6205 | |
| 6279 | 6206 | |
| @@ -6295,7 +6222,7 @@ class EncodingWithFacet: | ||
| 6295 | 6222 | column: FacetFieldDef | None = None |
| 6296 | 6223 | """Horizontal facets for trellis plots.""" |
| 6297 | 6224 | |
| 6298 | - detail: FieldDef | list[FieldDef] | None = None | |
| 6225 | + detail: FieldDefElement | list[FieldDefElement] | None = None | |
| 6299 | 6226 | """Additional levels of detail for grouping data in aggregate views and |
| 6300 | 6227 | in line and area marks without mapping data to a specific visual channel. |
| 6301 | 6228 | """ |
| @@ -6340,16 +6267,16 @@ class EncodingWithFacet: | ||
| 6340 | 6267 | tooltip: TextDefWithCondition | None = None |
| 6341 | 6268 | """The tooltip text to show upon mouse hover.""" |
| 6342 | 6269 | |
| 6343 | - x: XClass | None = None | |
| 6270 | + x: PositionFieldDef | ValueDef | None = None | |
| 6344 | 6271 | """X coordinates of the marks, or width of horizontal `"bar"` and `"area"`.""" |
| 6345 | 6272 | |
| 6346 | - x2: X2Class | None = None | |
| 6273 | + x2: FieldDefElement | ValueDef | None = None | |
| 6347 | 6274 | """X2 coordinates for ranged `"area"`, `"bar"`, `"rect"`, and `"rule"`.""" |
| 6348 | 6275 | |
| 6349 | - y: XClass | None = None | |
| 6276 | + y: PositionFieldDef | ValueDef | None = None | |
| 6350 | 6277 | """Y coordinates of the marks, or height of vertical `"bar"` and `"area"`.""" |
| 6351 | 6278 | |
| 6352 | - y2: X2Class | None = None | |
| 6279 | + y2: FieldDefElement | ValueDef | None = None | |
| 6353 | 6280 | """Y2 coordinates for ranged `"area"`, `"bar"`, `"rect"`, and `"rule"`.""" |
| 6354 | 6281 | |
| 6355 | 6282 | @staticmethod |
| @@ -6357,7 +6284,7 @@ class EncodingWithFacet: | ||
| 6357 | 6284 | assert isinstance(obj, dict) |
| 6358 | 6285 | color = from_union([MarkPropDefWithCondition.from_dict, from_none], obj.get("color")) |
| 6359 | 6286 | column = from_union([FacetFieldDef.from_dict, from_none], obj.get("column")) |
| 6360 | - detail = from_union([FieldDef.from_dict, lambda x: from_list(FieldDef.from_dict, x), from_none], obj.get("detail")) | |
| 6287 | + detail = from_union([FieldDefElement.from_dict, lambda x: from_list(FieldDefElement.from_dict, x), from_none], obj.get("detail")) | |
| 6361 | 6288 | href = from_union([DefWithCondition.from_dict, from_none], obj.get("href")) |
| 6362 | 6289 | opacity = from_union([MarkPropDefWithCondition.from_dict, from_none], obj.get("opacity")) |
| 6363 | 6290 | order = from_union([OrderFieldDef.from_dict, lambda x: from_list(OrderFieldDef.from_dict, x), from_none], obj.get("order")) |
| @@ -6366,10 +6293,10 @@ class EncodingWithFacet: | ||
| 6366 | 6293 | size = from_union([MarkPropDefWithCondition.from_dict, from_none], obj.get("size")) |
| 6367 | 6294 | text = from_union([TextDefWithCondition.from_dict, from_none], obj.get("text")) |
| 6368 | 6295 | tooltip = from_union([TextDefWithCondition.from_dict, from_none], obj.get("tooltip")) |
| 6369 | - x = from_union([XClass.from_dict, from_none], obj.get("x")) | |
| 6370 | - x2 = from_union([X2Class.from_dict, from_none], obj.get("x2")) | |
| 6371 | - y = from_union([XClass.from_dict, from_none], obj.get("y")) | |
| 6372 | - y2 = from_union([X2Class.from_dict, from_none], obj.get("y2")) | |
| 6296 | + x = from_union([lambda x: from_union([PositionFieldDef.from_dict, ValueDef.from_dict], x), from_none], obj.get("x")) | |
| 6297 | + x2 = from_union([lambda x: from_union([FieldDefElement.from_dict, ValueDef.from_dict], x), from_none], obj.get("x2")) | |
| 6298 | + y = from_union([lambda x: from_union([PositionFieldDef.from_dict, ValueDef.from_dict], x), from_none], obj.get("y")) | |
| 6299 | + y2 = from_union([lambda x: from_union([FieldDefElement.from_dict, ValueDef.from_dict], x), from_none], obj.get("y2")) | |
| 6373 | 6300 | return EncodingWithFacet(color, column, detail, href, opacity, order, row, shape, size, text, tooltip, x, x2, y, y2) |
| 6374 | 6301 | |
| 6375 | 6302 | def to_dict(self) -> dict: |
| @@ -6379,7 +6306,7 @@ class EncodingWithFacet: | ||
| 6379 | 6306 | if self.column is not None: |
| 6380 | 6307 | result["column"] = from_union([lambda x: to_class(FacetFieldDef, x), from_none], self.column) |
| 6381 | 6308 | if self.detail is not None: |
| 6382 | - result["detail"] = from_union([lambda x: to_class(FieldDef, x), lambda x: from_list(lambda x: to_class(FieldDef, x), x), from_none], self.detail) | |
| 6309 | + result["detail"] = from_union([lambda x: to_class(FieldDefElement, x), lambda x: from_list(lambda x: to_class(FieldDefElement, x), x), from_none], self.detail) | |
| 6383 | 6310 | if self.href is not None: |
| 6384 | 6311 | result["href"] = from_union([lambda x: to_class(DefWithCondition, x), from_none], self.href) |
| 6385 | 6312 | if self.opacity is not None: |
| @@ -6397,13 +6324,13 @@ class EncodingWithFacet: | ||
| 6397 | 6324 | if self.tooltip is not None: |
| 6398 | 6325 | result["tooltip"] = from_union([lambda x: to_class(TextDefWithCondition, x), from_none], self.tooltip) |
| 6399 | 6326 | if self.x is not None: |
| 6400 | - result["x"] = from_union([lambda x: to_class(XClass, x), from_none], self.x) | |
| 6327 | + result["x"] = from_union([lambda x: from_union([lambda x: to_class(PositionFieldDef, x), lambda x: to_class(ValueDef, x)], x), from_none], self.x) | |
| 6401 | 6328 | if self.x2 is not None: |
| 6402 | - result["x2"] = from_union([lambda x: to_class(X2Class, x), from_none], self.x2) | |
| 6329 | + result["x2"] = from_union([lambda x: from_union([lambda x: to_class(FieldDefElement, x), lambda x: to_class(ValueDef, x)], x), from_none], self.x2) | |
| 6403 | 6330 | if self.y is not None: |
| 6404 | - result["y"] = from_union([lambda x: to_class(XClass, x), from_none], self.y) | |
| 6331 | + result["y"] = from_union([lambda x: from_union([lambda x: to_class(PositionFieldDef, x), lambda x: to_class(ValueDef, x)], x), from_none], self.y) | |
| 6405 | 6332 | if self.y2 is not None: |
| 6406 | - result["y2"] = from_union([lambda x: to_class(X2Class, x), from_none], self.y2) | |
| 6333 | + result["y2"] = from_union([lambda x: from_union([lambda x: to_class(FieldDefElement, x), lambda x: to_class(ValueDef, x)], x), from_none], self.y2) | |
| 6407 | 6334 | return result |
| 6408 | 6335 | |
| 6409 | 6336 | |
| @@ -6449,7 +6376,7 @@ class Encoding: | ||
| 6449 | 6376 | _Note:_ See the scale documentation for more information about customizing [color |
| 6450 | 6377 | scheme](scale.html#scheme). |
| 6451 | 6378 | """ |
| 6452 | - detail: FieldDef | list[FieldDef] | None = None | |
| 6379 | + detail: FieldDefElement | list[FieldDefElement] | None = None | |
| 6453 | 6380 | """Additional levels of detail for grouping data in aggregate views and |
| 6454 | 6381 | in line and area marks without mapping data to a specific visual channel. |
| 6455 | 6382 | """ |
| @@ -6491,23 +6418,23 @@ class Encoding: | ||
| 6491 | 6418 | tooltip: TextDefWithCondition | None = None |
| 6492 | 6419 | """The tooltip text to show upon mouse hover.""" |
| 6493 | 6420 | |
| 6494 | - x: XClass | None = None | |
| 6421 | + x: PositionFieldDef | ValueDef | None = None | |
| 6495 | 6422 | """X coordinates of the marks, or width of horizontal `"bar"` and `"area"`.""" |
| 6496 | 6423 | |
| 6497 | - x2: X2Class | None = None | |
| 6424 | + x2: FieldDefElement | ValueDef | None = None | |
| 6498 | 6425 | """X2 coordinates for ranged `"area"`, `"bar"`, `"rect"`, and `"rule"`.""" |
| 6499 | 6426 | |
| 6500 | - y: XClass | None = None | |
| 6427 | + y: PositionFieldDef | ValueDef | None = None | |
| 6501 | 6428 | """Y coordinates of the marks, or height of vertical `"bar"` and `"area"`.""" |
| 6502 | 6429 | |
| 6503 | - y2: X2Class | None = None | |
| 6430 | + y2: FieldDefElement | ValueDef | None = None | |
| 6504 | 6431 | """Y2 coordinates for ranged `"area"`, `"bar"`, `"rect"`, and `"rule"`.""" |
| 6505 | 6432 | |
| 6506 | 6433 | @staticmethod |
| 6507 | 6434 | def from_dict(obj: Any) -> 'Encoding': |
| 6508 | 6435 | assert isinstance(obj, dict) |
| 6509 | 6436 | color = from_union([MarkPropDefWithCondition.from_dict, from_none], obj.get("color")) |
| 6510 | - detail = from_union([FieldDef.from_dict, lambda x: from_list(FieldDef.from_dict, x), from_none], obj.get("detail")) | |
| 6437 | + detail = from_union([FieldDefElement.from_dict, lambda x: from_list(FieldDefElement.from_dict, x), from_none], obj.get("detail")) | |
| 6511 | 6438 | href = from_union([DefWithCondition.from_dict, from_none], obj.get("href")) |
| 6512 | 6439 | opacity = from_union([MarkPropDefWithCondition.from_dict, from_none], obj.get("opacity")) |
| 6513 | 6440 | order = from_union([OrderFieldDef.from_dict, lambda x: from_list(OrderFieldDef.from_dict, x), from_none], obj.get("order")) |
| @@ -6515,10 +6442,10 @@ class Encoding: | ||
| 6515 | 6442 | size = from_union([MarkPropDefWithCondition.from_dict, from_none], obj.get("size")) |
| 6516 | 6443 | text = from_union([TextDefWithCondition.from_dict, from_none], obj.get("text")) |
| 6517 | 6444 | tooltip = from_union([TextDefWithCondition.from_dict, from_none], obj.get("tooltip")) |
| 6518 | - x = from_union([XClass.from_dict, from_none], obj.get("x")) | |
| 6519 | - x2 = from_union([X2Class.from_dict, from_none], obj.get("x2")) | |
| 6520 | - y = from_union([XClass.from_dict, from_none], obj.get("y")) | |
| 6521 | - y2 = from_union([X2Class.from_dict, from_none], obj.get("y2")) | |
| 6445 | + x = from_union([lambda x: from_union([PositionFieldDef.from_dict, ValueDef.from_dict], x), from_none], obj.get("x")) | |
| 6446 | + x2 = from_union([lambda x: from_union([FieldDefElement.from_dict, ValueDef.from_dict], x), from_none], obj.get("x2")) | |
| 6447 | + y = from_union([lambda x: from_union([PositionFieldDef.from_dict, ValueDef.from_dict], x), from_none], obj.get("y")) | |
| 6448 | + y2 = from_union([lambda x: from_union([FieldDefElement.from_dict, ValueDef.from_dict], x), from_none], obj.get("y2")) | |
| 6522 | 6449 | return Encoding(color, detail, href, opacity, order, shape, size, text, tooltip, x, x2, y, y2) |
| 6523 | 6450 | |
| 6524 | 6451 | def to_dict(self) -> dict: |
| @@ -6526,7 +6453,7 @@ class Encoding: | ||
| 6526 | 6453 | if self.color is not None: |
| 6527 | 6454 | result["color"] = from_union([lambda x: to_class(MarkPropDefWithCondition, x), from_none], self.color) |
| 6528 | 6455 | if self.detail is not None: |
| 6529 | - result["detail"] = from_union([lambda x: to_class(FieldDef, x), lambda x: from_list(lambda x: to_class(FieldDef, x), x), from_none], self.detail) | |
| 6456 | + result["detail"] = from_union([lambda x: to_class(FieldDefElement, x), lambda x: from_list(lambda x: to_class(FieldDefElement, x), x), from_none], self.detail) | |
| 6530 | 6457 | if self.href is not None: |
| 6531 | 6458 | result["href"] = from_union([lambda x: to_class(DefWithCondition, x), from_none], self.href) |
| 6532 | 6459 | if self.opacity is not None: |
| @@ -6542,13 +6469,13 @@ class Encoding: | ||
| 6542 | 6469 | if self.tooltip is not None: |
| 6543 | 6470 | result["tooltip"] = from_union([lambda x: to_class(TextDefWithCondition, x), from_none], self.tooltip) |
| 6544 | 6471 | if self.x is not None: |
| 6545 | - result["x"] = from_union([lambda x: to_class(XClass, x), from_none], self.x) | |
| 6472 | + result["x"] = from_union([lambda x: from_union([lambda x: to_class(PositionFieldDef, x), lambda x: to_class(ValueDef, x)], x), from_none], self.x) | |
| 6546 | 6473 | if self.x2 is not None: |
| 6547 | - result["x2"] = from_union([lambda x: to_class(X2Class, x), from_none], self.x2) | |
| 6474 | + result["x2"] = from_union([lambda x: from_union([lambda x: to_class(FieldDefElement, x), lambda x: to_class(ValueDef, x)], x), from_none], self.x2) | |
| 6548 | 6475 | if self.y is not None: |
| 6549 | - result["y"] = from_union([lambda x: to_class(XClass, x), from_none], self.y) | |
| 6476 | + result["y"] = from_union([lambda x: from_union([lambda x: to_class(PositionFieldDef, x), lambda x: to_class(ValueDef, x)], x), from_none], self.y) | |
| 6550 | 6477 | if self.y2 is not None: |
| 6551 | - result["y2"] = from_union([lambda x: to_class(X2Class, x), from_none], self.y2) | |
| 6478 | + result["y2"] = from_union([lambda x: from_union([lambda x: to_class(FieldDefElement, x), lambda x: to_class(ValueDef, x)], x), from_none], self.y2) | |
| 6552 | 6479 | return result |
Aschema-ruby/test/inputs/schema/named-class-union.schema/default/TopLevel.rb+73 −0
| @@ -0,0 +1,73 @@ | ||
| 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.op.foo | |
| 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 | + Hash = Strict::Hash | |
| 19 | + String = Strict::String | |
| 20 | +end | |
| 21 | + | |
| 22 | +class Foo < Dry::Struct | |
| 23 | + attribute :foo, Types::String.optional | |
| 24 | + attribute :bar, Types::String.optional | |
| 25 | + | |
| 26 | + def self.from_dynamic!(d) | |
| 27 | + d = Types::Hash[d] | |
| 28 | + new( | |
| 29 | + foo: d["foo"], | |
| 30 | + bar: d["bar"], | |
| 31 | + ) | |
| 32 | + end | |
| 33 | + | |
| 34 | + def self.from_json!(json) | |
| 35 | + from_dynamic!(JSON.parse(json)) | |
| 36 | + end | |
| 37 | + | |
| 38 | + def to_dynamic | |
| 39 | + { | |
| 40 | + "foo" => foo, | |
| 41 | + "bar" => bar, | |
| 42 | + } | |
| 43 | + end | |
| 44 | + | |
| 45 | + def to_json(options = nil) | |
| 46 | + JSON.generate(to_dynamic, options) | |
| 47 | + end | |
| 48 | +end | |
| 49 | + | |
| 50 | +class TopLevel < Dry::Struct | |
| 51 | + attribute :op, Foo | |
| 52 | + | |
| 53 | + def self.from_dynamic!(d) | |
| 54 | + d = Types::Hash[d] | |
| 55 | + new( | |
| 56 | + op: Foo.from_dynamic!(d.fetch("op")), | |
| 57 | + ) | |
| 58 | + end | |
| 59 | + | |
| 60 | + def self.from_json!(json) | |
| 61 | + from_dynamic!(JSON.parse(json)) | |
| 62 | + end | |
| 63 | + | |
| 64 | + def to_dynamic | |
| 65 | + { | |
| 66 | + "op" => op.to_dynamic, | |
| 67 | + } | |
| 68 | + end | |
| 69 | + | |
| 70 | + def to_json(options = nil) | |
| 71 | + JSON.generate(to_dynamic, options) | |
| 72 | + end | |
| 73 | +end |
Aschema-rust/test/inputs/schema/named-class-union.schema/default/module_under_test.rs+26 −0
| @@ -0,0 +1,26 @@ | ||
| 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 op: Foo, | |
| 19 | +} | |
| 20 | + | |
| 21 | +#[derive(Debug, Clone, Serialize, Deserialize)] | |
| 22 | +pub struct Foo { | |
| 23 | + pub foo: Option<String>, | |
| 24 | + | |
| 25 | + pub bar: Option<String>, | |
| 26 | +} |
Aschema-scala3-upickle/test/inputs/schema/named-class-union.schema/default/TopLevel.scala+17 −0
| @@ -0,0 +1,17 @@ | ||
| 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 op : Foo | |
| 12 | +) derives Encoder.AsObject, Decoder | |
| 13 | + | |
| 14 | +case class Foo ( | |
| 15 | + val foo : Option[String] = None, | |
| 16 | + val bar : Option[String] = None | |
| 17 | +) derives Encoder.AsObject, Decoder |
Aschema-scala3/test/inputs/schema/named-class-union.schema/default/TopLevel.scala+75 −0
| @@ -0,0 +1,75 @@ | ||
| 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 op : Foo | |
| 70 | +) derives OptionPickler.ReadWriter | |
| 71 | + | |
| 72 | +case class Foo ( | |
| 73 | + val foo : Option[String] = None, | |
| 74 | + val bar : Option[String] = None | |
| 75 | +) derives OptionPickler.ReadWriter |
Aschema-schema/test/inputs/schema/named-class-union.schema/default/TopLevel.schema+33 −0
| @@ -0,0 +1,33 @@ | ||
| 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 | + "op": { | |
| 10 | + "$ref": "#/definitions/Foo" | |
| 11 | + } | |
| 12 | + }, | |
| 13 | + "required": [ | |
| 14 | + "op" | |
| 15 | + ], | |
| 16 | + "title": "TopLevel" | |
| 17 | + }, | |
| 18 | + "Foo": { | |
| 19 | + "type": "object", | |
| 20 | + "additionalProperties": false, | |
| 21 | + "properties": { | |
| 22 | + "foo": { | |
| 23 | + "type": "string" | |
| 24 | + }, | |
| 25 | + "bar": { | |
| 26 | + "type": "string" | |
| 27 | + } | |
| 28 | + }, | |
| 29 | + "required": [], | |
| 30 | + "title": "Foo" | |
| 31 | + } | |
| 32 | + } | |
| 33 | +} |
Aschema-swift/test/inputs/schema/named-class-union.schema/default/quicktype.swift+134 −0
| @@ -0,0 +1,134 @@ | ||
| 1 | +// This file was generated from JSON Schema using quicktype, do not modify it directly. | |
| 2 | +// To parse the JSON, add this file to your project and do: | |
| 3 | +// | |
| 4 | +// let topLevel = try TopLevel(json) | |
| 5 | + | |
| 6 | +import Foundation | |
| 7 | + | |
| 8 | +// MARK: - TopLevel | |
| 9 | +struct TopLevel: Codable { | |
| 10 | + let op: Foo | |
| 11 | + | |
| 12 | + enum CodingKeys: String, CodingKey { | |
| 13 | + case op = "op" | |
| 14 | + } | |
| 15 | +} | |
| 16 | + | |
| 17 | +// MARK: TopLevel convenience initializers and mutators | |
| 18 | + | |
| 19 | +extension TopLevel { | |
| 20 | + init(data: Data) throws { | |
| 21 | + self = try newJSONDecoder().decode(TopLevel.self, from: data) | |
| 22 | + } | |
| 23 | + | |
| 24 | + init(_ json: String, using encoding: String.Encoding = .utf8) throws { | |
| 25 | + guard let data = json.data(using: encoding) else { | |
| 26 | + throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) | |
| 27 | + } | |
| 28 | + try self.init(data: data) | |
| 29 | + } | |
| 30 | + | |
| 31 | + init(fromURL url: URL) throws { | |
| 32 | + try self.init(data: try Data(contentsOf: url)) | |
| 33 | + } | |
| 34 | + | |
| 35 | + func with( | |
| 36 | + op: Foo? = nil | |
| 37 | + ) -> TopLevel { | |
| 38 | + return TopLevel( | |
| 39 | + op: op ?? self.op | |
| 40 | + ) | |
| 41 | + } | |
| 42 | + | |
| 43 | + func jsonData() throws -> Data { | |
| 44 | + return try newJSONEncoder().encode(self) | |
| 45 | + } | |
| 46 | + | |
| 47 | + func jsonString(encoding: String.Encoding = .utf8) throws -> String? { | |
| 48 | + return String(data: try self.jsonData(), encoding: encoding) | |
| 49 | + } | |
| 50 | +} | |
| 51 | + | |
| 52 | +// MARK: - Foo | |
| 53 | +struct Foo: Codable { | |
| 54 | + let foo: String? | |
| 55 | + let bar: String? | |
| 56 | + | |
| 57 | + enum CodingKeys: String, CodingKey { | |
| 58 | + case foo = "foo" | |
| 59 | + case bar = "bar" | |
| 60 | + } | |
| 61 | +} | |
| 62 | + | |
| 63 | +// MARK: Foo convenience initializers and mutators | |
| 64 | + | |
| 65 | +extension Foo { | |
| 66 | + init(data: Data) throws { | |
| 67 | + self = try newJSONDecoder().decode(Foo.self, from: data) | |
| 68 | + } | |
| 69 | + | |
| 70 | + init(_ json: String, using encoding: String.Encoding = .utf8) throws { | |
| 71 | + guard let data = json.data(using: encoding) else { | |
| 72 | + throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) | |
| 73 | + } | |
| 74 | + try self.init(data: data) | |
| 75 | + } | |
| 76 | + | |
| 77 | + init(fromURL url: URL) throws { | |
| 78 | + try self.init(data: try Data(contentsOf: url)) | |
| 79 | + } | |
| 80 | + | |
| 81 | + func with( | |
| 82 | + foo: String?? = nil, | |
| 83 | + bar: String?? = nil | |
| 84 | + ) -> Foo { | |
| 85 | + return Foo( | |
| 86 | + foo: foo ?? self.foo, | |
| 87 | + bar: bar ?? self.bar | |
| 88 | + ) | |
| 89 | + } | |
| 90 | + | |
| 91 | + func jsonData() throws -> Data { | |
| 92 | + return try newJSONEncoder().encode(self) | |
| 93 | + } | |
| 94 | + | |
| 95 | + func jsonString(encoding: String.Encoding = .utf8) throws -> String? { | |
| 96 | + return String(data: try self.jsonData(), encoding: encoding) | |
| 97 | + } | |
| 98 | +} | |
| 99 | + | |
| 100 | +// MARK: - Helper functions for creating encoders and decoders | |
| 101 | + | |
| 102 | +func newJSONDecoder() -> JSONDecoder { | |
| 103 | + let decoder = JSONDecoder() | |
| 104 | + decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in | |
| 105 | + let container = try decoder.singleValueContainer() | |
| 106 | + let dateStr = try container.decode(String.self) | |
| 107 | + | |
| 108 | + let formatter = DateFormatter() | |
| 109 | + formatter.calendar = Calendar(identifier: .iso8601) | |
| 110 | + formatter.locale = Locale(identifier: "en_US_POSIX") | |
| 111 | + formatter.timeZone = TimeZone(secondsFromGMT: 0) | |
| 112 | + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX" | |
| 113 | + if let date = formatter.date(from: dateStr) { | |
| 114 | + return date | |
| 115 | + } | |
| 116 | + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX" | |
| 117 | + if let date = formatter.date(from: dateStr) { | |
| 118 | + return date | |
| 119 | + } | |
| 120 | + throw DecodingError.typeMismatch(Date.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not decode date")) | |
| 121 | + }) | |
| 122 | + return decoder | |
| 123 | +} | |
| 124 | + | |
| 125 | +func newJSONEncoder() -> JSONEncoder { | |
| 126 | + let encoder = JSONEncoder() | |
| 127 | + let formatter = DateFormatter() | |
| 128 | + formatter.calendar = Calendar(identifier: .iso8601) | |
| 129 | + formatter.locale = Locale(identifier: "en_US_POSIX") | |
| 130 | + formatter.timeZone = TimeZone(secondsFromGMT: 0) | |
| 131 | + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX" | |
| 132 | + encoder.dateEncodingStrategy = .formatted(formatter) | |
| 133 | + return encoder | |
| 134 | +} |
Aschema-typescript-zod/test/inputs/schema/named-class-union.schema/default/TopLevel.ts+192 −0
| @@ -0,0 +1,192 @@ | ||
| 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 | + op: Foo; | |
| 12 | +} | |
| 13 | + | |
| 14 | +export interface Foo { | |
| 15 | + foo?: string; | |
| 16 | + bar?: string; | |
| 17 | +} | |
| 18 | + | |
| 19 | +// Converts JSON strings to/from your types | |
| 20 | +// and asserts the results of JSON.parse at runtime | |
| 21 | +export class Convert { | |
| 22 | + public static toTopLevel(json: string): TopLevel { | |
| 23 | + return cast(JSON.parse(json), r("TopLevel")); | |
| 24 | + } | |
| 25 | + | |
| 26 | + public static topLevelToJson(value: TopLevel): string { | |
| 27 | + return JSON.stringify(uncast(value, r("TopLevel")), null, 2); | |
| 28 | + } | |
| 29 | +} | |
| 30 | + | |
| 31 | +function invalidValue(typ: any, val: any, key: any, parent: any = ''): never { | |
| 32 | + const prettyTyp = prettyTypeName(typ); | |
| 33 | + const parentText = parent ? ` on ${parent}` : ''; | |
| 34 | + const keyText = key ? ` for key "${key}"` : ''; | |
| 35 | + throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`); | |
| 36 | +} | |
| 37 | + | |
| 38 | +function prettyTypeName(typ: any): string { | |
| 39 | + if (Array.isArray(typ)) { | |
| 40 | + if (typ.length === 2 && typ[0] === undefined) { | |
| 41 | + return `an optional ${prettyTypeName(typ[1])}`; | |
| 42 | + } else { | |
| 43 | + return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`; | |
| 44 | + } | |
| 45 | + } else if (typeof typ === "object" && typ.literal !== undefined) { | |
| 46 | + return typ.literal; | |
| 47 | + } else { | |
| 48 | + return typeof typ; | |
| 49 | + } | |
| 50 | +} | |
| 51 | + | |
| 52 | +function jsonToJSProps(typ: any): any { | |
| 53 | + if (typ.jsonToJS === undefined) { | |
| 54 | + const map: any = {}; | |
| 55 | + typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ }); | |
| 56 | + typ.jsonToJS = map; | |
| 57 | + } | |
| 58 | + return typ.jsonToJS; | |
| 59 | +} | |
| 60 | + | |
| 61 | +function jsToJSONProps(typ: any): any { | |
| 62 | + if (typ.jsToJSON === undefined) { | |
| 63 | + const map: any = {}; | |
| 64 | + typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ }); | |
| 65 | + typ.jsToJSON = map; | |
| 66 | + } | |
| 67 | + return typ.jsToJSON; | |
| 68 | +} | |
| 69 | + | |
| 70 | +function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any { | |
| 71 | + function transformPrimitive(typ: string, val: any): any { | |
| 72 | + if (typeof typ === typeof val) return val; | |
| 73 | + return invalidValue(typ, val, key, parent); | |
| 74 | + } | |
| 75 | + | |
| 76 | + function transformUnion(typs: any[], val: any): any { | |
| 77 | + // val must validate against one typ in typs | |
| 78 | + const l = typs.length; | |
| 79 | + for (let i = 0; i < l; i++) { | |
| 80 | + const typ = typs[i]; | |
| 81 | + try { | |
| 82 | + return transform(val, typ, getProps); | |
| 83 | + } catch (_) {} | |
| 84 | + } | |
| 85 | + return invalidValue(typs, val, key, parent); | |
| 86 | + } | |
| 87 | + | |
| 88 | + function transformEnum(cases: string[], val: any): any { | |
| 89 | + if (cases.indexOf(val) !== -1) return val; | |
| 90 | + return invalidValue(cases.map(a => { return l(a); }), val, key, parent); | |
| 91 | + } | |
| 92 | + | |
| 93 | + function transformArray(typ: any, val: any): any { | |
| 94 | + // val must be an array with no invalid elements | |
| 95 | + if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent); | |
| 96 | + return val.map(el => transform(el, typ, getProps)); | |
| 97 | + } | |
| 98 | + | |
| 99 | + function transformDate(val: any): any { | |
| 100 | + if (val === null) { | |
| 101 | + return null; | |
| 102 | + } | |
| 103 | + const d = new Date(val); | |
| 104 | + if (isNaN(d.valueOf())) { | |
| 105 | + return invalidValue(l("Date"), val, key, parent); | |
| 106 | + } | |
| 107 | + return d; | |
| 108 | + } | |
| 109 | + | |
| 110 | + function transformObject(props: { [k: string]: any }, additional: any, val: any): any { | |
| 111 | + if (val === null || typeof val !== "object" || Array.isArray(val)) { | |
| 112 | + return invalidValue(l(ref || "object"), val, key, parent); | |
| 113 | + } | |
| 114 | + const result: any = {}; | |
| 115 | + Object.getOwnPropertyNames(props).forEach(key => { | |
| 116 | + const prop = props[key]; | |
| 117 | + const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined; | |
| 118 | + result[prop.key] = transform(v, prop.typ, getProps, key, ref); | |
| 119 | + }); | |
| 120 | + Object.getOwnPropertyNames(val).forEach(key => { | |
| 121 | + if (!Object.prototype.hasOwnProperty.call(props, key)) { | |
| 122 | + result[key] = transform(val[key], additional, getProps, key, ref); | |
| 123 | + } | |
| 124 | + }); | |
| 125 | + return result; | |
| 126 | + } | |
| 127 | + | |
| 128 | + if (typ === "any") return val; | |
| 129 | + if (typ === null) { | |
| 130 | + if (val === null) return val; | |
| 131 | + return invalidValue(typ, val, key, parent); | |
| 132 | + } | |
| 133 | + if (typ === false) return invalidValue(typ, val, key, parent); | |
| 134 | + let ref: any = undefined; | |
| 135 | + while (typeof typ === "object" && typ.ref !== undefined) { | |
| 136 | + ref = typ.ref; | |
| 137 | + typ = typeMap[typ.ref]; | |
| 138 | + } | |
| 139 | + if (Array.isArray(typ)) return transformEnum(typ, val); | |
| 140 | + if (typeof typ === "object") { | |
| 141 | + return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val) | |
| 142 | + : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val) | |
| 143 | + : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val) | |
| 144 | + : invalidValue(typ, val, key, parent); | |
| 145 | + } | |
| 146 | + // Numbers can be parsed by Date but shouldn't be. | |
| 147 | + if (typ === Date && typeof val !== "number") return transformDate(val); | |
| 148 | + return transformPrimitive(typ, val); | |
| 149 | +} | |
| 150 | + | |
| 151 | +function cast<T>(val: any, typ: any): T { | |
| 152 | + return transform(val, typ, jsonToJSProps); | |
| 153 | +} | |
| 154 | + | |
| 155 | +function uncast<T>(val: T, typ: any): any { | |
| 156 | + return transform(val, typ, jsToJSONProps); | |
| 157 | +} | |
| 158 | + | |
| 159 | +function l(typ: any) { | |
| 160 | + return { literal: typ }; | |
| 161 | +} | |
| 162 | + | |
| 163 | +function a(typ: any) { | |
| 164 | + return { arrayItems: typ }; | |
| 165 | +} | |
| 166 | + | |
| 167 | +function u(...typs: any[]) { | |
| 168 | + return { unionMembers: typs }; | |
| 169 | +} | |
| 170 | + | |
| 171 | +function o(props: any[], additional: any) { | |
| 172 | + return { props, additional }; | |
| 173 | +} | |
| 174 | + | |
| 175 | +function m(additional: any) { | |
| 176 | + const props: any[] = []; | |
| 177 | + return { props, additional }; | |
| 178 | +} | |
| 179 | + | |
| 180 | +function r(name: string) { | |
| 181 | + return { ref: name }; | |
| 182 | +} | |
| 183 | + | |
| 184 | +const typeMap: any = { | |
| 185 | + "TopLevel": o([ | |
| 186 | + { json: "op", js: "op", typ: r("Foo") }, | |
| 187 | + ], false), | |
| 188 | + "Foo": o([ | |
| 189 | + { json: "foo", js: "foo", typ: u(undefined, "") }, | |
| 190 | + { json: "bar", js: "bar", typ: u(undefined, "") }, | |
| 191 | + ], false), | |
| 192 | +}; |
Aschema-typescript/test/inputs/schema/named-class-union.schema/default/TopLevel.ts+13 −0
| @@ -0,0 +1,13 @@ | ||
| 1 | +import * as z from "zod"; | |
| 2 | + | |
| 3 | + | |
| 4 | +export const FooSchema = z.object({ | |
| 5 | + "foo": z.string().optional(), | |
| 6 | + "bar": z.string().optional(), | |
| 7 | +}); | |
| 8 | +export type Foo = z.infer<typeof FooSchema>; | |
| 9 | + | |
| 10 | +export const TopLevelSchema = z.object({ | |
| 11 | + "op": FooSchema, | |
| 12 | +}); | |
| 13 | +export type TopLevel = z.infer<typeof TopLevelSchema>; |
No generated files match these filters.