Generated-output differences

quicktype output changed between the PR base and tested PR merge revisions.
← Back to the pull request
1test cases
34files differ
0modified
34new
0deleted
2,505changed lines
+2,505 −0insertions / deletions
Base a49b94e8f6f1b319a4da9fb15d57ef13ba316ddc · PR merge 831640258d1963fe39be503c7de02102df6ae711 · Head 44c17a24ace19949c15e6eb012399c7deb6e2b4f · raw patch
Test case

test/inputs/schema/json-pointer-escaped-keys.schema

34 generated files · +2,505 −0
Aschema-cplusplusdefault / quicktype.hpp+94 −0
@@ -0,0 +1,94 @@
1+// To parse this JSON data, first install
2+//
3+// json.hpp https://github.com/nlohmann/json
4+//
5+// Then include this file, and then do
6+//
7+// TopLevel data = nlohmann::json::parse(jsonString);
8+
9+#pragma once
10+
11+#include "json.hpp"
12+
13+#include <optional>
14+#include <stdexcept>
15+#include <regex>
16+
17+namespace quicktype {
18+ using nlohmann::json;
19+
20+ #ifndef NLOHMANN_UNTYPED_quicktype_HELPER
21+ #define NLOHMANN_UNTYPED_quicktype_HELPER
22+ inline json get_untyped(const json & j, const char * property) {
23+ if (j.find(property) != j.end()) {
24+ return j.at(property).get<json>();
25+ }
26+ return json();
27+ }
28+
29+ inline json get_untyped(const json & j, std::string property) {
30+ return get_untyped(j, property.data());
31+ }
32+ #endif
33+
34+ class MZ {
35+ public:
36+ MZ() = default;
37+ virtual ~MZ() = default;
38+
39+ private:
40+ double value;
41+
42+ public:
43+ const double & get_value() const { return value; }
44+ double & get_mutable_value() { return value; }
45+ void set_value(const double & value) { this->value = value; }
46+ };
47+
48+ class TopLevel {
49+ public:
50+ TopLevel() = default;
51+ virtual ~TopLevel() = default;
52+
53+ private:
54+ MZ mz;
55+ std::string tilde;
56+
57+ public:
58+ const MZ & get_mz() const { return mz; }
59+ MZ & get_mutable_mz() { return mz; }
60+ void set_mz(const MZ & value) { this->mz = value; }
61+
62+ const std::string & get_tilde() const { return tilde; }
63+ std::string & get_mutable_tilde() { return tilde; }
64+ void set_tilde(const std::string & value) { this->tilde = value; }
65+ };
66+}
67+
68+namespace quicktype {
69+ void from_json(const json & j, MZ & x);
70+ void to_json(json & j, const MZ & x);
71+
72+ void from_json(const json & j, TopLevel & x);
73+ void to_json(json & j, const TopLevel & x);
74+
75+ inline void from_json(const json & j, MZ& x) {
76+ x.set_value(j.at("value").get<double>());
77+ }
78+
79+ inline void to_json(json & j, const MZ & x) {
80+ j = json::object();
81+ j["value"] = x.get_value();
82+ }
83+
84+ inline void from_json(const json & j, TopLevel& x) {
85+ x.set_mz(j.at("mz").get<MZ>());
86+ x.set_tilde(j.at("tilde").get<std::string>());
87+ }
88+
89+ inline void to_json(json & j, const TopLevel & x) {
90+ j = json::object();
91+ j["mz"] = x.get_mz();
92+ j["tilde"] = x.get_tilde();
93+ }
94+}
Aschema-csharp-recordsdefault / 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 record TopLevel
27+ {
28+ [JsonProperty("mz", Required = Required.Always)]
29+ public MZ Mz { get; set; }
30+
31+ [JsonProperty("tilde", Required = Required.Always)]
32+ public string Tilde { get; set; }
33+ }
34+
35+ public partial record MZ
36+ {
37+ [JsonProperty("value", Required = Required.Always)]
38+ public double Value { get; set; }
39+ }
40+
41+ public partial record 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-SystemTextJsondefault / 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("mz")]
27+ public MZ Mz { get; set; }
28+
29+ [JsonRequired]
30+ [JsonPropertyName("tilde")]
31+ public string Tilde { get; set; }
32+ }
33+
34+ public partial class MZ
35+ {
36+ [JsonRequired]
37+ [JsonPropertyName("value")]
38+ public double Value { 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-csharpdefault / 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("mz", Required = Required.Always)]
29+ public MZ Mz { get; set; }
30+
31+ [JsonProperty("tilde", Required = Required.Always)]
32+ public string Tilde { get; set; }
33+ }
34+
35+ public partial class MZ
36+ {
37+ [JsonProperty("value", Required = Required.Always)]
38+ public double Value { 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-dartdefault / 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 MZ mz;
13+ final String tilde;
14+
15+ TopLevel({
16+ required this.mz,
17+ required this.tilde,
18+ });
19+
20+ factory TopLevel.fromJson(Map<String, dynamic> json) => TopLevel(
21+ mz: MZ.fromJson(json["mz"]),
22+ tilde: json["tilde"],
23+ );
24+
25+ Map<String, dynamic> toJson() => {
26+ "mz": mz.toJson(),
27+ "tilde": tilde,
28+ };
29+}
30+
31+class MZ {
32+ final double value;
33+
34+ MZ({
35+ required this.value,
36+ });
37+
38+ factory MZ.fromJson(Map<String, dynamic> json) => MZ(
39+ value: json["value"]?.toDouble(),
40+ );
41+
42+ Map<String, dynamic> toJson() => {
43+ "value": value,
44+ };
45+}
Aschema-elixirdefault / QuickType.ex+75 −0
@@ -0,0 +1,75 @@
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 MZ do
9+ @enforce_keys [:value]
10+ defstruct [:value]
11+
12+ @type t :: %__MODULE__{
13+ value: float()
14+ }
15+
16+ def from_map(m) do
17+ %MZ{
18+ value: m["value"],
19+ }
20+ end
21+
22+ def from_json(json) do
23+ json
24+ |> Jason.decode!()
25+ |> from_map()
26+ end
27+
28+ def to_map(struct) do
29+ %{
30+ "value" => struct.value,
31+ }
32+ end
33+
34+ def to_json(struct) do
35+ struct
36+ |> to_map()
37+ |> Jason.encode!()
38+ end
39+end
40+
41+defmodule TopLevel do
42+ @enforce_keys [:mz, :tilde]
43+ defstruct [:mz, :tilde]
44+
45+ @type t :: %__MODULE__{
46+ mz: MZ.t(),
47+ tilde: String.t()
48+ }
49+
50+ def from_map(m) do
51+ %TopLevel{
52+ mz: MZ.from_map(m["mz"]),
53+ tilde: m["tilde"],
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+ "mz" => MZ.to_map(struct.mz),
66+ "tilde" => struct.tilde,
67+ }
68+ end
69+
70+ def to_json(struct) do
71+ struct
72+ |> to_map()
73+ |> Jason.encode!()
74+ end
75+end
Aschema-elmdefault / QuickType.elm+70 −0
@@ -0,0 +1,70 @@
1+-- To decode the JSON data, add this file to your project, run
2+--
3+-- elm install NoRedInk/elm-json-decode-pipeline
4+--
5+-- add these imports
6+--
7+-- import Json.Decode exposing (decodeString)
8+-- import QuickType exposing (quickType)
9+--
10+-- and you're off to the races with
11+--
12+-- decodeString quickType myJsonString
13+
14+module QuickType exposing
15+ ( QuickType
16+ , quickTypeToString
17+ , quickType
18+ , MZ
19+ )
20+
21+import Json.Decode as Jdec
22+import Json.Decode.Pipeline as Jpipe
23+import Json.Encode as Jenc
24+import Dict exposing (Dict)
25+
26+type alias QuickType =
27+ { mz : MZ
28+ , tilde : String
29+ }
30+
31+type alias MZ =
32+ { value : Float
33+ }
34+
35+-- decoders and encoders
36+
37+quickTypeToString : QuickType -> String
38+quickTypeToString r = Jenc.encode 0 (encodeQuickType r)
39+
40+quickType : Jdec.Decoder QuickType
41+quickType =
42+ Jdec.succeed QuickType
43+ |> Jpipe.required "mz" mz
44+ |> Jpipe.required "tilde" Jdec.string
45+
46+encodeQuickType : QuickType -> Jenc.Value
47+encodeQuickType x =
48+ Jenc.object
49+ [ ("mz", encodeMZ x.mz)
50+ , ("tilde", Jenc.string x.tilde)
51+ ]
52+
53+mz : Jdec.Decoder MZ
54+mz =
55+ Jdec.succeed MZ
56+ |> Jpipe.required "value" Jdec.float
57+
58+encodeMZ : MZ -> Jenc.Value
59+encodeMZ x =
60+ Jenc.object
61+ [ ("value", Jenc.float x.value)
62+ ]
63+
64+--- encoder helpers
65+
66+makeNullableEncoder : (a -> Jenc.Value) -> Maybe a -> Jenc.Value
67+makeNullableEncoder f m =
68+ case m of
69+ Just x -> f x
70+ Nothing -> Jenc.null
Aschema-flowdefault / TopLevel.js+199 −0
@@ -0,0 +1,199 @@
1+// @flow
2+
3+// To parse this data:
4+//
5+// const Convert = require("./TopLevel");
6+//
7+// const topLevel = Convert.toTopLevel(json);
8+//
9+// These functions will throw an error if the JSON doesn't
10+// match the expected interface, even if the JSON is valid.
11+
12+export type TopLevel = {
13+ mz: MZ;
14+ tilde: string;
15+ [property: string]: mixed;
16+};
17+
18+export type MZ = {
19+ value: number;
20+ [property: string]: mixed;
21+};
22+
23+// Converts JSON strings to/from your types
24+// and asserts the results of JSON.parse at runtime
25+function toTopLevel(json: string): TopLevel {
26+ return cast(JSON.parse(json), r("TopLevel"));
27+}
28+
29+function topLevelToJson(value: TopLevel): string {
30+ return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
31+}
32+
33+function invalidValue(typ: any, val: any, key: any, parent: any = '') {
34+ const prettyTyp = prettyTypeName(typ);
35+ const parentText = parent ? ` on ${parent}` : '';
36+ const keyText = key ? ` for key "${key}"` : '';
37+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
38+}
39+
40+function prettyTypeName(typ: any): string {
41+ if (Array.isArray(typ)) {
42+ if (typ.length === 2 && typ[0] === undefined) {
43+ return `an optional ${prettyTypeName(typ[1])}`;
44+ } else {
45+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
46+ }
47+ } else if (typeof typ === "object" && typ.literal !== undefined) {
48+ return typ.literal;
49+ } else {
50+ return typeof typ;
51+ }
52+}
53+
54+function jsonToJSProps(typ: any): any {
55+ if (typ.jsonToJS === undefined) {
56+ const map: any = {};
57+ typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
58+ typ.jsonToJS = map;
59+ }
60+ return typ.jsonToJS;
61+}
62+
63+function jsToJSONProps(typ: any): any {
64+ if (typ.jsToJSON === undefined) {
65+ const map: any = {};
66+ typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
67+ typ.jsToJSON = map;
68+ }
69+ return typ.jsToJSON;
70+}
71+
72+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
73+ function transformPrimitive(typ: string, val: any): any {
74+ if (typeof typ === typeof val) return val;
75+ return invalidValue(typ, val, key, parent);
76+ }
77+
78+ function transformUnion(typs: any[], val: any): any {
79+ // val must validate against one typ in typs
80+ const l = typs.length;
81+ for (let i = 0; i < l; i++) {
82+ const typ = typs[i];
83+ try {
84+ return transform(val, typ, getProps);
85+ } catch (_) {}
86+ }
87+ return invalidValue(typs, val, key, parent);
88+ }
89+
90+ function transformEnum(cases: string[], val: any): any {
91+ if (cases.indexOf(val) !== -1) return val;
92+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
93+ }
94+
95+ function transformArray(typ: any, val: any): any {
96+ // val must be an array with no invalid elements
97+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
98+ return val.map(el => transform(el, typ, getProps));
99+ }
100+
101+ function transformDate(val: any): any {
102+ if (val === null) {
103+ return null;
104+ }
105+ const d = new Date(val);
106+ if (isNaN(d.valueOf())) {
107+ return invalidValue(l("Date"), val, key, parent);
108+ }
109+ return d;
110+ }
111+
112+ function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
113+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
114+ return invalidValue(l(ref || "object"), val, key, parent);
115+ }
116+ const result: any = {};
117+ Object.getOwnPropertyNames(props).forEach(key => {
118+ const prop = props[key];
119+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
120+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
121+ });
122+ Object.getOwnPropertyNames(val).forEach(key => {
123+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
124+ result[key] = transform(val[key], additional, getProps, key, ref);
125+ }
126+ });
127+ return result;
128+ }
129+
130+ if (typ === "any") return val;
131+ if (typ === null) {
132+ if (val === null) return val;
133+ return invalidValue(typ, val, key, parent);
134+ }
135+ if (typ === false) return invalidValue(typ, val, key, parent);
136+ let ref: any = undefined;
137+ while (typeof typ === "object" && typ.ref !== undefined) {
138+ ref = typ.ref;
139+ typ = typeMap[typ.ref];
140+ }
141+ if (Array.isArray(typ)) return transformEnum(typ, val);
142+ if (typeof typ === "object") {
143+ return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
144+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
145+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
146+ : invalidValue(typ, val, key, parent);
147+ }
148+ // Numbers can be parsed by Date but shouldn't be.
149+ if (typ === Date && typeof val !== "number") return transformDate(val);
150+ return transformPrimitive(typ, val);
151+}
152+
153+function cast<T>(val: any, typ: any): T {
154+ return transform(val, typ, jsonToJSProps);
155+}
156+
157+function uncast<T>(val: T, typ: any): any {
158+ return transform(val, typ, jsToJSONProps);
159+}
160+
161+function l(typ: any) {
162+ return { literal: typ };
163+}
164+
165+function a(typ: any) {
166+ return { arrayItems: typ };
167+}
168+
169+function u(...typs: any[]) {
170+ return { unionMembers: typs };
171+}
172+
173+function o(props: any[], additional: any) {
174+ return { props, additional };
175+}
176+
177+function m(additional: any) {
178+ const props: any[] = [];
179+ return { props, additional };
180+}
181+
182+function r(name: string) {
183+ return { ref: name };
184+}
185+
186+const typeMap: any = {
187+ "TopLevel": o([
188+ { json: "mz", js: "mz", typ: r("MZ") },
189+ { json: "tilde", js: "tilde", typ: "" },
190+ ], "any"),
191+ "MZ": o([
192+ { json: "value", js: "value", typ: 3.14 },
193+ ], "any"),
194+};
195+
196+module.exports = {
197+ "topLevelToJson": topLevelToJson,
198+ "toTopLevel": toTopLevel,
199+};
Aschema-golangdefault / 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+ Mz MZ `json:"mz"`
23+ Tilde string `json:"tilde"`
24+}
25+
26+type MZ struct {
27+ Value float64 `json:"value"`
28+}
Aschema-haskelldefault / QuickType.hs+48 −0
@@ -0,0 +1,48 @@
1+{-# LANGUAGE StrictData #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+
4+module QuickType
5+ ( QuickType (..)
6+ , MZ (..)
7+ , decodeTopLevel
8+ ) where
9+
10+import Data.Aeson
11+import Data.Aeson.Types (emptyObject)
12+import Data.ByteString.Lazy (ByteString)
13+import Data.HashMap.Strict (HashMap)
14+import Data.Text (Text)
15+
16+data QuickType = QuickType
17+ { mzQuickType :: MZ
18+ , tildeQuickType :: Text
19+ } deriving (Show)
20+
21+data MZ = MZ
22+ { valueMZ :: Float
23+ } deriving (Show)
24+
25+decodeTopLevel :: ByteString -> Maybe QuickType
26+decodeTopLevel = decode
27+
28+instance ToJSON QuickType where
29+ toJSON (QuickType mzQuickType tildeQuickType) =
30+ object
31+ [ "mz" .= mzQuickType
32+ , "tilde" .= tildeQuickType
33+ ]
34+
35+instance FromJSON QuickType where
36+ parseJSON (Object v) = QuickType
37+ <$> v .: "mz"
38+ <*> v .: "tilde"
39+
40+instance ToJSON MZ where
41+ toJSON (MZ valueMZ) =
42+ object
43+ [ "value" .= valueMZ
44+ ]
45+
46+instance FromJSON MZ where
47+ parseJSON (Object v) = MZ
48+ <$> v .: "value"
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / Converter.java+121 −0
@@ -0,0 +1,121 @@
1+// To use this code, add the following Maven dependency to your project:
2+//
3+//
4+// com.fasterxml.jackson.core : jackson-databind : 2.9.0
5+//
6+//
7+// Import this package:
8+//
9+// import io.quicktype.Converter;
10+//
11+// Then you can deserialize a JSON string with
12+//
13+// TopLevel data = Converter.fromJsonString(jsonString);
14+
15+package io.quicktype;
16+
17+import java.io.IOException;
18+import com.fasterxml.jackson.databind.*;
19+import com.fasterxml.jackson.databind.module.SimpleModule;
20+import com.fasterxml.jackson.core.JsonParser;
21+import com.fasterxml.jackson.core.JsonProcessingException;
22+import java.util.*;
23+import java.util.Date;
24+import java.text.SimpleDateFormat;
25+
26+public class Converter {
27+ // Date-time helpers
28+
29+ private static final String[] DATE_TIME_FORMATS = {
30+ "yyyy-MM-dd'T'HH:mm:ss.SX",
31+ "yyyy-MM-dd'T'HH:mm:ss.S",
32+ "yyyy-MM-dd'T'HH:mm:ssX",
33+ "yyyy-MM-dd'T'HH:mm:ss",
34+ "yyyy-MM-dd HH:mm:ss.SX",
35+ "yyyy-MM-dd HH:mm:ss.S",
36+ "yyyy-MM-dd HH:mm:ssX",
37+ "yyyy-MM-dd HH:mm:ss",
38+ "HH:mm:ss.SZ",
39+ "HH:mm:ss.S",
40+ "HH:mm:ssZ",
41+ "HH:mm:ss",
42+ "yyyy-MM-dd",
43+ };
44+
45+ public static Date parseAllDateTimeString(String str) {
46+ for (String format : DATE_TIME_FORMATS) {
47+ try {
48+ return new SimpleDateFormat(format).parse(str);
49+ } catch (Exception ex) {
50+ // Ignored
51+ }
52+ }
53+ return null;
54+ }
55+
56+ public static String serializeDateTime(Date datetime) {
57+ return new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ").format(datetime);
58+ }
59+
60+ public static String serializeDate(Date datetime) {
61+ return new SimpleDateFormat("yyyy-MM-dd").format(datetime);
62+ }
63+
64+ public static String serializeTime(Date datetime) {
65+ return new SimpleDateFormat("hh:mm:ssZ").format(datetime);
66+ }
67+ // Serialize/deserialize helpers
68+
69+ public static TopLevel fromJsonString(String json) throws IOException {
70+ return getObjectReader().readValue(json);
71+ }
72+
73+ public static String toJsonString(TopLevel obj) throws JsonProcessingException {
74+ return getObjectWriter().writeValueAsString(obj);
75+ }
76+
77+ private static ObjectReader reader;
78+ private static ObjectWriter writer;
79+
80+ private static void instantiateMapper() {
81+ ObjectMapper mapper = new ObjectMapper();
82+ mapper.findAndRegisterModules();
83+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
84+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
85+ SimpleModule module = new SimpleModule();
86+ module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
87+ @Override
88+ public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
89+ String value = jsonParser.getText();
90+ return Converter.parseAllDateTimeString(value);
91+ }
92+ });
93+ module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
94+ @Override
95+ public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
96+ String value = jsonParser.getText();
97+ return Converter.parseAllDateTimeString(value);
98+ }
99+ });
100+ module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
101+ @Override
102+ public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
103+ String value = jsonParser.getText();
104+ return Converter.parseAllDateTimeString(value);
105+ }
106+ });
107+ mapper.registerModule(module);
108+ reader = mapper.readerFor(TopLevel.class);
109+ writer = mapper.writerFor(TopLevel.class);
110+ }
111+
112+ private static ObjectReader getObjectReader() {
113+ if (reader == null) instantiateMapper();
114+ return reader;
115+ }
116+
117+ private static ObjectWriter getObjectWriter() {
118+ if (writer == null) instantiateMapper();
119+ return writer;
120+ }
121+}
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / MZ.java+12 −0
@@ -0,0 +1,12 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class MZ {
6+ private double value;
7+
8+ @JsonProperty("value")
9+ public double getValue() { return value; }
10+ @JsonProperty("value")
11+ public void setValue(double value) { this.value = value; }
12+}
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / TopLevel.java+18 −0
@@ -0,0 +1,18 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class TopLevel {
6+ private MZ mz;
7+ private String tilde;
8+
9+ @JsonProperty("mz")
10+ public MZ getMz() { return mz; }
11+ @JsonProperty("mz")
12+ public void setMz(MZ value) { this.mz = value; }
13+
14+ @JsonProperty("tilde")
15+ public String getTilde() { return tilde; }
16+ @JsonProperty("tilde")
17+ public void setTilde(String value) { this.tilde = value; }
18+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / Converter.java+101 −0
@@ -0,0 +1,101 @@
1+// To use this code, add the following Maven dependency to your project:
2+//
3+//
4+// com.fasterxml.jackson.core : jackson-databind : 2.9.0
5+// com.fasterxml.jackson.datatype : jackson-datatype-jsr310 : 2.9.0
6+//
7+// Import this package:
8+//
9+// import io.quicktype.Converter;
10+//
11+// Then you can deserialize a JSON string with
12+//
13+// TopLevel data = Converter.fromJsonString(jsonString);
14+
15+package io.quicktype;
16+
17+import java.io.IOException;
18+import com.fasterxml.jackson.databind.*;
19+import com.fasterxml.jackson.databind.module.SimpleModule;
20+import com.fasterxml.jackson.core.JsonParser;
21+import com.fasterxml.jackson.core.JsonProcessingException;
22+import java.util.*;
23+import java.time.LocalDate;
24+import java.time.OffsetDateTime;
25+import java.time.OffsetTime;
26+import java.time.ZoneOffset;
27+import java.time.ZonedDateTime;
28+import java.time.format.DateTimeFormatter;
29+import java.time.format.DateTimeFormatterBuilder;
30+import java.time.temporal.ChronoField;
31+
32+public class Converter {
33+ // Date-time helpers
34+
35+ private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
36+ .appendOptional(DateTimeFormatter.ISO_DATE_TIME)
37+ .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
38+ .appendOptional(DateTimeFormatter.ISO_INSTANT)
39+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX"))
40+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX"))
41+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
42+ .toFormatter()
43+ .withZone(ZoneOffset.UTC);
44+
45+ public static OffsetDateTime parseDateTimeString(String str) {
46+ return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();
47+ }
48+
49+ private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
50+ .appendOptional(DateTimeFormatter.ISO_TIME)
51+ .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)
52+ .parseDefaulting(ChronoField.YEAR, 2020)
53+ .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
54+ .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
55+ .toFormatter()
56+ .withZone(ZoneOffset.UTC);
57+
58+ public static OffsetTime parseTimeString(String str) {
59+ return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();
60+ }
61+ // Serialize/deserialize helpers
62+
63+ public static TopLevel fromJsonString(String json) throws IOException {
64+ return getObjectReader().readValue(json);
65+ }
66+
67+ public static String toJsonString(TopLevel obj) throws JsonProcessingException {
68+ return getObjectWriter().writeValueAsString(obj);
69+ }
70+
71+ private static ObjectReader reader;
72+ private static ObjectWriter writer;
73+
74+ private static void instantiateMapper() {
75+ ObjectMapper mapper = new ObjectMapper();
76+ mapper.findAndRegisterModules();
77+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
78+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
79+ SimpleModule module = new SimpleModule();
80+ module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
81+ @Override
82+ public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
83+ String value = jsonParser.getText();
84+ return Converter.parseDateTimeString(value);
85+ }
86+ });
87+ mapper.registerModule(module);
88+ reader = mapper.readerFor(TopLevel.class);
89+ writer = mapper.writerFor(TopLevel.class);
90+ }
91+
92+ private static ObjectReader getObjectReader() {
93+ if (reader == null) instantiateMapper();
94+ return reader;
95+ }
96+
97+ private static ObjectWriter getObjectWriter() {
98+ if (writer == null) instantiateMapper();
99+ return writer;
100+ }
101+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / MZ.java+12 −0
@@ -0,0 +1,12 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class MZ {
6+ private double value;
7+
8+ @JsonProperty("value")
9+ public double getValue() { return value; }
10+ @JsonProperty("value")
11+ public void setValue(double value) { this.value = value; }
12+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / TopLevel.java+18 −0
@@ -0,0 +1,18 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class TopLevel {
6+ private MZ mz;
7+ private String tilde;
8+
9+ @JsonProperty("mz")
10+ public MZ getMz() { return mz; }
11+ @JsonProperty("mz")
12+ public void setMz(MZ value) { this.mz = value; }
13+
14+ @JsonProperty("tilde")
15+ public String getTilde() { return tilde; }
16+ @JsonProperty("tilde")
17+ public void setTilde(String value) { this.tilde = value; }
18+}
Aschema-javadefault / src / main / java / io / quicktype / Converter.java+101 −0
@@ -0,0 +1,101 @@
1+// To use this code, add the following Maven dependency to your project:
2+//
3+//
4+// com.fasterxml.jackson.core : jackson-databind : 2.9.0
5+// com.fasterxml.jackson.datatype : jackson-datatype-jsr310 : 2.9.0
6+//
7+// Import this package:
8+//
9+// import io.quicktype.Converter;
10+//
11+// Then you can deserialize a JSON string with
12+//
13+// TopLevel data = Converter.fromJsonString(jsonString);
14+
15+package io.quicktype;
16+
17+import java.io.IOException;
18+import com.fasterxml.jackson.databind.*;
19+import com.fasterxml.jackson.databind.module.SimpleModule;
20+import com.fasterxml.jackson.core.JsonParser;
21+import com.fasterxml.jackson.core.JsonProcessingException;
22+import java.util.*;
23+import java.time.LocalDate;
24+import java.time.OffsetDateTime;
25+import java.time.OffsetTime;
26+import java.time.ZoneOffset;
27+import java.time.ZonedDateTime;
28+import java.time.format.DateTimeFormatter;
29+import java.time.format.DateTimeFormatterBuilder;
30+import java.time.temporal.ChronoField;
31+
32+public class Converter {
33+ // Date-time helpers
34+
35+ private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
36+ .appendOptional(DateTimeFormatter.ISO_DATE_TIME)
37+ .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
38+ .appendOptional(DateTimeFormatter.ISO_INSTANT)
39+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX"))
40+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX"))
41+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
42+ .toFormatter()
43+ .withZone(ZoneOffset.UTC);
44+
45+ public static OffsetDateTime parseDateTimeString(String str) {
46+ return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();
47+ }
48+
49+ private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
50+ .appendOptional(DateTimeFormatter.ISO_TIME)
51+ .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)
52+ .parseDefaulting(ChronoField.YEAR, 2020)
53+ .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
54+ .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
55+ .toFormatter()
56+ .withZone(ZoneOffset.UTC);
57+
58+ public static OffsetTime parseTimeString(String str) {
59+ return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();
60+ }
61+ // Serialize/deserialize helpers
62+
63+ public static TopLevel fromJsonString(String json) throws IOException {
64+ return getObjectReader().readValue(json);
65+ }
66+
67+ public static String toJsonString(TopLevel obj) throws JsonProcessingException {
68+ return getObjectWriter().writeValueAsString(obj);
69+ }
70+
71+ private static ObjectReader reader;
72+ private static ObjectWriter writer;
73+
74+ private static void instantiateMapper() {
75+ ObjectMapper mapper = new ObjectMapper();
76+ mapper.findAndRegisterModules();
77+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
78+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
79+ SimpleModule module = new SimpleModule();
80+ module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
81+ @Override
82+ public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
83+ String value = jsonParser.getText();
84+ return Converter.parseDateTimeString(value);
85+ }
86+ });
87+ mapper.registerModule(module);
88+ reader = mapper.readerFor(TopLevel.class);
89+ writer = mapper.writerFor(TopLevel.class);
90+ }
91+
92+ private static ObjectReader getObjectReader() {
93+ if (reader == null) instantiateMapper();
94+ return reader;
95+ }
96+
97+ private static ObjectWriter getObjectWriter() {
98+ if (writer == null) instantiateMapper();
99+ return writer;
100+ }
101+}
Aschema-javadefault / src / main / java / io / quicktype / MZ.java+12 −0
@@ -0,0 +1,12 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class MZ {
6+ private double value;
7+
8+ @JsonProperty("value")
9+ public double getValue() { return value; }
10+ @JsonProperty("value")
11+ public void setValue(double value) { this.value = value; }
12+}
Aschema-javadefault / src / main / java / io / quicktype / TopLevel.java+18 −0
@@ -0,0 +1,18 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class TopLevel {
6+ private MZ mz;
7+ private String tilde;
8+
9+ @JsonProperty("mz")
10+ public MZ getMz() { return mz; }
11+ @JsonProperty("mz")
12+ public void setMz(MZ value) { this.mz = value; }
13+
14+ @JsonProperty("tilde")
15+ public String getTilde() { return tilde; }
16+ @JsonProperty("tilde")
17+ public void setTilde(String value) { this.tilde = value; }
18+}
Aschema-javascriptdefault / 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: "mz", js: "mz", typ: r("MZ") },
176+ { json: "tilde", js: "tilde", typ: "" },
177+ ], "any"),
178+ "MZ": o([
179+ { json: "value", js: "value", typ: 3.14 },
180+ ], "any"),
181+};
182+
183+module.exports = {
184+ "topLevelToJson": topLevelToJson,
185+ "toTopLevel": toTopLevel,
186+};
Aschema-kotlin-jacksondefault / TopLevel.kt+38 −0
@@ -0,0 +1,38 @@
1+// To parse the JSON, install jackson-module-kotlin and do:
2+//
3+// val topLevel = TopLevel.fromJson(jsonString)
4+
5+package quicktype
6+
7+import com.fasterxml.jackson.annotation.*
8+import com.fasterxml.jackson.core.*
9+import com.fasterxml.jackson.databind.*
10+import com.fasterxml.jackson.databind.deser.std.StdDeserializer
11+import com.fasterxml.jackson.databind.module.SimpleModule
12+import com.fasterxml.jackson.databind.node.*
13+import com.fasterxml.jackson.databind.ser.std.StdSerializer
14+import com.fasterxml.jackson.module.kotlin.*
15+
16+val mapper = jacksonObjectMapper().apply {
17+ propertyNamingStrategy = PropertyNamingStrategy.LOWER_CAMEL_CASE
18+ setSerializationInclusion(JsonInclude.Include.NON_NULL)
19+}
20+
21+data class TopLevel (
22+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
23+ val mz: MZ,
24+
25+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
26+ val tilde: String
27+) {
28+ fun toJson() = mapper.writeValueAsString(this)
29+
30+ companion object {
31+ fun fromJson(json: String) = mapper.readValue<TopLevel>(json)
32+ }
33+}
34+
35+data class MZ (
36+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
37+ val value: Double
38+)
Aschema-kotlindefault / TopLevel.kt+24 −0
@@ -0,0 +1,24 @@
1+// To parse the JSON, install Klaxon and do:
2+//
3+// val topLevel = TopLevel.fromJson(jsonString)
4+
5+package quicktype
6+
7+import com.beust.klaxon.*
8+
9+private val klaxon = Klaxon()
10+
11+data class TopLevel (
12+ val mz: MZ,
13+ val tilde: String
14+) {
15+ public fun toJson() = klaxon.toJsonString(this)
16+
17+ companion object {
18+ public fun fromJson(json: String) = klaxon.parse<TopLevel>(json)
19+ }
20+}
21+
22+data class MZ (
23+ val value: Double
24+)
Aschema-kotlinxdefault / 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 mz: MZ,
16+ val tilde: String
17+)
18+
19+@Serializable
20+data class MZ (
21+ val value: Double
22+)
Aschema-phpdefault / TopLevel.php+253 −0
@@ -0,0 +1,253 @@
1+<?php
2+declare(strict_types=1);
3+
4+// This is an autogenerated file:TopLevel
5+
6+class TopLevel {
7+ private MZ $mz; // json:mz Required
8+ private string $tilde; // json:tilde Required
9+
10+ /**
11+ * @param MZ $mz
12+ * @param string $tilde
13+ */
14+ public function __construct(MZ $mz, string $tilde) {
15+ $this->mz = $mz;
16+ $this->tilde = $tilde;
17+ }
18+
19+ /**
20+ * @param stdClass $value
21+ * @throws Exception
22+ * @return MZ
23+ */
24+ public static function fromMz(stdClass $value): MZ {
25+ return MZ::from($value); /*class*/
26+ }
27+
28+ /**
29+ * @throws Exception
30+ * @return stdClass
31+ */
32+ public function toMz(): stdClass {
33+ if (TopLevel::validateMz($this->mz)) {
34+ return $this->mz->to(); /*class*/
35+ }
36+ throw new Exception('never get to this TopLevel::mz');
37+ }
38+
39+ /**
40+ * @param MZ
41+ * @return bool
42+ * @throws Exception
43+ */
44+ public static function validateMz(MZ $value): bool {
45+ $value->validate();
46+ return true;
47+ }
48+
49+ /**
50+ * @throws Exception
51+ * @return MZ
52+ */
53+ public function getMz(): MZ {
54+ if (TopLevel::validateMz($this->mz)) {
55+ return $this->mz;
56+ }
57+ throw new Exception('never get to getMz TopLevel::mz');
58+ }
59+
60+ /**
61+ * @return MZ
62+ */
63+ public static function sampleMz(): MZ {
64+ return MZ::sample(); /*31:mz*/
65+ }
66+
67+ /**
68+ * @param string $value
69+ * @throws Exception
70+ * @return string
71+ */
72+ public static function fromTilde(string $value): string {
73+ return $value; /*string*/
74+ }
75+
76+ /**
77+ * @throws Exception
78+ * @return string
79+ */
80+ public function toTilde(): string {
81+ if (TopLevel::validateTilde($this->tilde)) {
82+ return $this->tilde; /*string*/
83+ }
84+ throw new Exception('never get to this TopLevel::tilde');
85+ }
86+
87+ /**
88+ * @param string
89+ * @return bool
90+ * @throws Exception
91+ */
92+ public static function validateTilde(string $value): bool {
93+ return true;
94+ }
95+
96+ /**
97+ * @throws Exception
98+ * @return string
99+ */
100+ public function getTilde(): string {
101+ if (TopLevel::validateTilde($this->tilde)) {
102+ return $this->tilde;
103+ }
104+ throw new Exception('never get to getTilde TopLevel::tilde');
105+ }
106+
107+ /**
108+ * @return string
109+ */
110+ public static function sampleTilde(): string {
111+ return 'TopLevel::tilde::32'; /*32:tilde*/
112+ }
113+
114+ /**
115+ * @throws Exception
116+ * @return bool
117+ */
118+ public function validate(): bool {
119+ return TopLevel::validateMz($this->mz)
120+ || TopLevel::validateTilde($this->tilde);
121+ }
122+
123+ /**
124+ * @return stdClass
125+ * @throws Exception
126+ */
127+ public function to(): stdClass {
128+ $out = new stdClass();
129+ $out->{'mz'} = $this->toMz();
130+ $out->{'tilde'} = $this->toTilde();
131+ return $out;
132+ }
133+
134+ /**
135+ * @param stdClass $obj
136+ * @return TopLevel
137+ * @throws Exception
138+ */
139+ public static function from(stdClass $obj): TopLevel {
140+ return new TopLevel(
141+ TopLevel::fromMz($obj->{'mz'})
142+ ,TopLevel::fromTilde($obj->{'tilde'})
143+ );
144+ }
145+
146+ /**
147+ * @return TopLevel
148+ */
149+ public static function sample(): TopLevel {
150+ return new TopLevel(
151+ TopLevel::sampleMz()
152+ ,TopLevel::sampleTilde()
153+ );
154+ }
155+}
156+
157+// This is an autogenerated file:MZ
158+
159+class MZ {
160+ private float $value; // json:value Required
161+
162+ /**
163+ * @param float $value
164+ */
165+ public function __construct(float $value) {
166+ $this->value = $value;
167+ }
168+
169+ /**
170+ * @param float $value
171+ * @throws Exception
172+ * @return float
173+ */
174+ public static function fromValue(float $value): float {
175+ return $value; /*float*/
176+ }
177+
178+ /**
179+ * @throws Exception
180+ * @return float
181+ */
182+ public function toValue(): float {
183+ if (MZ::validateValue($this->value)) {
184+ return $this->value; /*float*/
185+ }
186+ throw new Exception('never get to this MZ::value');
187+ }
188+
189+ /**
190+ * @param float
191+ * @return bool
192+ * @throws Exception
193+ */
194+ public static function validateValue(float $value): bool {
195+ return true;
196+ }
197+
198+ /**
199+ * @throws Exception
200+ * @return float
201+ */
202+ public function getValue(): float {
203+ if (MZ::validateValue($this->value)) {
204+ return $this->value;
205+ }
206+ throw new Exception('never get to getValue MZ::value');
207+ }
208+
209+ /**
210+ * @return float
211+ */
212+ public static function sampleValue(): float {
213+ return 31.031; /*31:value*/
214+ }
215+
216+ /**
217+ * @throws Exception
218+ * @return bool
219+ */
220+ public function validate(): bool {
221+ return MZ::validateValue($this->value);
222+ }
223+
224+ /**
225+ * @return stdClass
226+ * @throws Exception
227+ */
228+ public function to(): stdClass {
229+ $out = new stdClass();
230+ $out->{'value'} = $this->toValue();
231+ return $out;
232+ }
233+
234+ /**
235+ * @param stdClass $obj
236+ * @return MZ
237+ * @throws Exception
238+ */
239+ public static function from(stdClass $obj): MZ {
240+ return new MZ(
241+ MZ::fromValue($obj->{'value'})
242+ );
243+ }
244+
245+ /**
246+ * @return MZ
247+ */
248+ public static function sample(): MZ {
249+ return new MZ(
250+ MZ::sampleValue()
251+ );
252+ }
253+}
Aschema-pikedefault / 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+ MZ mz; // json: "mz"
17+ string tilde; // json: "tilde"
18+
19+ string encode_json() {
20+ mapping(string:mixed) json = ([
21+ "mz" : mz,
22+ "tilde" : tilde,
23+ ]);
24+
25+ return Standards.JSON.encode(json);
26+ }
27+}
28+
29+TopLevel TopLevel_from_JSON(mixed json) {
30+ TopLevel retval = TopLevel();
31+
32+ retval.mz = json["mz"];
33+ retval.tilde = json["tilde"];
34+
35+ return retval;
36+}
37+
38+class MZ {
39+ float value; // json: "value"
40+
41+ string encode_json() {
42+ mapping(string:mixed) json = ([
43+ "value" : value,
44+ ]);
45+
46+ return Standards.JSON.encode(json);
47+ }
48+}
49+
50+MZ MZ_from_JSON(mixed json) {
51+ MZ retval = MZ();
52+
53+ retval.value = json["value"];
54+
55+ return retval;
56+}
Aschema-pythondefault / quicktype.py+68 −0
@@ -0,0 +1,68 @@
1+from dataclasses import dataclass
2+from typing import Any, TypeVar, Type, cast
3+
4+
5+T = TypeVar("T")
6+
7+
8+def from_float(x: Any) -> float:
9+ assert isinstance(x, (float, int)) and not isinstance(x, bool)
10+ return float(x)
11+
12+
13+def to_float(x: Any) -> float:
14+ assert isinstance(x, (int, float))
15+ return x
16+
17+
18+def from_str(x: Any) -> str:
19+ assert isinstance(x, str)
20+ return x
21+
22+
23+def to_class(c: Type[T], x: Any) -> dict:
24+ assert isinstance(x, c)
25+ return cast(Any, x).to_dict()
26+
27+
28+@dataclass
29+class MZ:
30+ value: float
31+
32+ @staticmethod
33+ def from_dict(obj: Any) -> 'MZ':
34+ assert isinstance(obj, dict)
35+ value = from_float(obj.get("value"))
36+ return MZ(value)
37+
38+ def to_dict(self) -> dict:
39+ result: dict = {}
40+ result["value"] = to_float(self.value)
41+ return result
42+
43+
44+@dataclass
45+class TopLevel:
46+ mz: MZ
47+ tilde: str
48+
49+ @staticmethod
50+ def from_dict(obj: Any) -> 'TopLevel':
51+ assert isinstance(obj, dict)
52+ mz = MZ.from_dict(obj.get("mz"))
53+ tilde = from_str(obj.get("tilde"))
54+ return TopLevel(mz, tilde)
55+
56+ def to_dict(self) -> dict:
57+ result: dict = {}
58+ result["mz"] = to_class(MZ, self.mz)
59+ result["tilde"] = from_str(self.tilde)
60+ return result
61+
62+
63+def top_level_from_dict(s: Any) -> TopLevel:
64+ return TopLevel.from_dict(s)
65+
66+
67+def top_level_to_dict(x: TopLevel) -> Any:
68+ return to_class(TopLevel, x)
Aschema-rubydefault / TopLevel.rb+74 −0
@@ -0,0 +1,74 @@
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.mz.value
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+ Double = Strict::Float | Strict::Integer
21+end
22+
23+class MZ < Dry::Struct
24+ attribute :value, Types::Double
25+
26+ def self.from_dynamic!(d)
27+ d = Types::Hash[d]
28+ new(
29+ value: d.fetch("value"),
30+ )
31+ end
32+
33+ def self.from_json!(json)
34+ from_dynamic!(JSON.parse(json))
35+ end
36+
37+ def to_dynamic
38+ {
39+ "value" => value,
40+ }
41+ end
42+
43+ def to_json(options = nil)
44+ JSON.generate(to_dynamic, options)
45+ end
46+end
47+
48+class TopLevel < Dry::Struct
49+ attribute :mz, MZ
50+ attribute :tilde, Types::String
51+
52+ def self.from_dynamic!(d)
53+ d = Types::Hash[d]
54+ new(
55+ mz: MZ.from_dynamic!(d.fetch("mz")),
56+ tilde: d.fetch("tilde"),
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+ "mz" => mz.to_dynamic,
67+ "tilde" => tilde,
68+ }
69+ end
70+
71+ def to_json(options = nil)
72+ JSON.generate(to_dynamic, options)
73+ end
74+end
Aschema-rustdefault / 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 mz: MZ,
19+
20+ pub tilde: String,
21+}
22+
23+#[derive(Debug, Clone, Serialize, Deserialize)]
24+pub struct MZ {
25+ pub value: f64,
26+}
Aschema-scala3-upickledefault / 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 mz : MZ,
70+ val tilde : String
71+) derives OptionPickler.ReadWriter
72+
73+case class MZ (
74+ val value : Double
75+) derives OptionPickler.ReadWriter
Aschema-scala3default / 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 mz : MZ,
12+ val tilde : String
13+) derives Encoder.AsObject, Decoder
14+
15+case class MZ (
16+ val value : Double
17+) derives Encoder.AsObject, Decoder
Aschema-schemadefault / TopLevel.schema+36 −0
@@ -0,0 +1,36 @@
1+{
2+ "$schema": "http://json-schema.org/draft-06/schema#",
3+ "$ref": "#/definitions/TopLevel",
4+ "definitions": {
5+ "TopLevel": {
6+ "type": "object",
7+ "additionalProperties": {},
8+ "properties": {
9+ "mz": {
10+ "$ref": "#/definitions/MZ"
11+ },
12+ "tilde": {
13+ "type": "string"
14+ }
15+ },
16+ "required": [
17+ "mz",
18+ "tilde"
19+ ],
20+ "title": "TopLevel"
21+ },
22+ "MZ": {
23+ "type": "object",
24+ "additionalProperties": {},
25+ "properties": {
26+ "value": {
27+ "type": "number"
28+ }
29+ },
30+ "required": [
31+ "value"
32+ ],
33+ "title": "MZ"
34+ }
35+ }
36+}
Aschema-swiftdefault / 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 mz: MZ
11+ let tilde: String
12+
13+ enum CodingKeys: String, CodingKey {
14+ case mz = "mz"
15+ case tilde = "tilde"
16+ }
17+}
18+
19+// MARK: TopLevel convenience initializers and mutators
20+
21+extension TopLevel {
22+ init(data: Data) throws {
23+ self = try newJSONDecoder().decode(TopLevel.self, from: data)
24+ }
25+
26+ init(_ json: String, using encoding: String.Encoding = .utf8) throws {
27+ guard let data = json.data(using: encoding) else {
28+ throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
29+ }
30+ try self.init(data: data)
31+ }
32+
33+ init(fromURL url: URL) throws {
34+ try self.init(data: try Data(contentsOf: url))
35+ }
36+
37+ func with(
38+ mz: MZ? = nil,
39+ tilde: String? = nil
40+ ) -> TopLevel {
41+ return TopLevel(
42+ mz: mz ?? self.mz,
43+ tilde: tilde ?? self.tilde
44+ )
45+ }
46+
47+ func jsonData() throws -> Data {
48+ return try newJSONEncoder().encode(self)
49+ }
50+
51+ func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
52+ return String(data: try self.jsonData(), encoding: encoding)
53+ }
54+}
55+
56+// MARK: - MZ
57+struct MZ: Codable {
58+ let value: Double
59+
60+ enum CodingKeys: String, CodingKey {
61+ case value = "value"
62+ }
63+}
64+
65+// MARK: MZ convenience initializers and mutators
66+
67+extension MZ {
68+ init(data: Data) throws {
69+ self = try newJSONDecoder().decode(MZ.self, from: data)
70+ }
71+
72+ init(_ json: String, using encoding: String.Encoding = .utf8) throws {
73+ guard let data = json.data(using: encoding) else {
74+ throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
75+ }
76+ try self.init(data: data)
77+ }
78+
79+ init(fromURL url: URL) throws {
80+ try self.init(data: try Data(contentsOf: url))
81+ }
82+
83+ func with(
84+ value: Double? = nil
85+ ) -> MZ {
86+ return MZ(
87+ value: value ?? self.value
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-zoddefault / TopLevel.ts+13 −0
@@ -0,0 +1,13 @@
1+import * as z from "zod";
2+
3+
4+export const MZSchema = z.object({
5+ "value": z.number(),
6+});
7+export type MZ = z.infer<typeof MZSchema>;
8+
9+export const TopLevelSchema = z.object({
10+ "mz": MZSchema,
11+ "tilde": z.string(),
12+});
13+export type TopLevel = z.infer<typeof TopLevelSchema>;
Aschema-typescriptdefault / TopLevel.ts+194 −0
@@ -0,0 +1,194 @@
1+// To parse this data:
2+//
3+// import { Convert, TopLevel } from "./TopLevel";
4+//
5+// const topLevel = Convert.toTopLevel(json);
6+//
7+// These functions will throw an error if the JSON doesn't
8+// match the expected interface, even if the JSON is valid.
9+
10+export interface TopLevel {
11+ mz: MZ;
12+ tilde: string;
13+ [property: string]: unknown;
14+}
15+
16+export interface MZ {
17+ value: number;
18+ [property: string]: unknown;
19+}
20+
21+// Converts JSON strings to/from your types
22+// and asserts the results of JSON.parse at runtime
23+export class Convert {
24+ public static toTopLevel(json: string): TopLevel {
25+ return cast(JSON.parse(json), r("TopLevel"));
26+ }
27+
28+ public static topLevelToJson(value: TopLevel): string {
29+ return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
30+ }
31+}
32+
33+function invalidValue(typ: any, val: any, key: any, parent: any = ''): never {
34+ const prettyTyp = prettyTypeName(typ);
35+ const parentText = parent ? ` on ${parent}` : '';
36+ const keyText = key ? ` for key "${key}"` : '';
37+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
38+}
39+
40+function prettyTypeName(typ: any): string {
41+ if (Array.isArray(typ)) {
42+ if (typ.length === 2 && typ[0] === undefined) {
43+ return `an optional ${prettyTypeName(typ[1])}`;
44+ } else {
45+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
46+ }
47+ } else if (typeof typ === "object" && typ.literal !== undefined) {
48+ return typ.literal;
49+ } else {
50+ return typeof typ;
51+ }
52+}
53+
54+function jsonToJSProps(typ: any): any {
55+ if (typ.jsonToJS === undefined) {
56+ const map: any = {};
57+ typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
58+ typ.jsonToJS = map;
59+ }
60+ return typ.jsonToJS;
61+}
62+
63+function jsToJSONProps(typ: any): any {
64+ if (typ.jsToJSON === undefined) {
65+ const map: any = {};
66+ typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
67+ typ.jsToJSON = map;
68+ }
69+ return typ.jsToJSON;
70+}
71+
72+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
73+ function transformPrimitive(typ: string, val: any): any {
74+ if (typeof typ === typeof val) return val;
75+ return invalidValue(typ, val, key, parent);
76+ }
77+
78+ function transformUnion(typs: any[], val: any): any {
79+ // val must validate against one typ in typs
80+ const l = typs.length;
81+ for (let i = 0; i < l; i++) {
82+ const typ = typs[i];
83+ try {
84+ return transform(val, typ, getProps);
85+ } catch (_) {}
86+ }
87+ return invalidValue(typs, val, key, parent);
88+ }
89+
90+ function transformEnum(cases: string[], val: any): any {
91+ if (cases.indexOf(val) !== -1) return val;
92+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
93+ }
94+
95+ function transformArray(typ: any, val: any): any {
96+ // val must be an array with no invalid elements
97+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
98+ return val.map(el => transform(el, typ, getProps));
99+ }
100+
101+ function transformDate(val: any): any {
102+ if (val === null) {
103+ return null;
104+ }
105+ const d = new Date(val);
106+ if (isNaN(d.valueOf())) {
107+ return invalidValue(l("Date"), val, key, parent);
108+ }
109+ return d;
110+ }
111+
112+ function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
113+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
114+ return invalidValue(l(ref || "object"), val, key, parent);
115+ }
116+ const result: any = {};
117+ Object.getOwnPropertyNames(props).forEach(key => {
118+ const prop = props[key];
119+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
120+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
121+ });
122+ Object.getOwnPropertyNames(val).forEach(key => {
123+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
124+ result[key] = transform(val[key], additional, getProps, key, ref);
125+ }
126+ });
127+ return result;
128+ }
129+
130+ if (typ === "any") return val;
131+ if (typ === null) {
132+ if (val === null) return val;
133+ return invalidValue(typ, val, key, parent);
134+ }
135+ if (typ === false) return invalidValue(typ, val, key, parent);
136+ let ref: any = undefined;
137+ while (typeof typ === "object" && typ.ref !== undefined) {
138+ ref = typ.ref;
139+ typ = typeMap[typ.ref];
140+ }
141+ if (Array.isArray(typ)) return transformEnum(typ, val);
142+ if (typeof typ === "object") {
143+ return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
144+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
145+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
146+ : invalidValue(typ, val, key, parent);
147+ }
148+ // Numbers can be parsed by Date but shouldn't be.
149+ if (typ === Date && typeof val !== "number") return transformDate(val);
150+ return transformPrimitive(typ, val);
151+}
152+
153+function cast<T>(val: any, typ: any): T {
154+ return transform(val, typ, jsonToJSProps);
155+}
156+
157+function uncast<T>(val: T, typ: any): any {
158+ return transform(val, typ, jsToJSONProps);
159+}
160+
161+function l(typ: any) {
162+ return { literal: typ };
163+}
164+
165+function a(typ: any) {
166+ return { arrayItems: typ };
167+}
168+
169+function u(...typs: any[]) {
170+ return { unionMembers: typs };
171+}
172+
173+function o(props: any[], additional: any) {
174+ return { props, additional };
175+}
176+
177+function m(additional: any) {
178+ const props: any[] = [];
179+ return { props, additional };
180+}
181+
182+function r(name: string) {
183+ return { ref: name };
184+}
185+
186+const typeMap: any = {
187+ "TopLevel": o([
188+ { json: "mz", js: "mz", typ: r("MZ") },
189+ { json: "tilde", js: "tilde", typ: "" },
190+ ], "any"),
191+ "MZ": o([
192+ { json: "value", js: "value", typ: 3.14 },
193+ ], "any"),
194+};
No generated files match these filters.