Generated-output differences

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

test/inputs/schema/default-value.schema

1 generated file · +2 −2
Mschema-pythondefault / quicktype.py+2 −2
@@ -19,12 +19,12 @@ def to_class(c: Type[T], x: Any) -> dict:
1919 class TopLevel:
2020 """An object with a scalar default"""
2121
22- id: int
22+ id: int = 0
2323
2424 @staticmethod
2525 def from_dict(obj: Any) -> 'TopLevel':
2626 assert isinstance(obj, dict)
27- id = from_int(obj.get("id"))
27+ id = from_int(obj.get("id", 0))
2828 return TopLevel(id)
2929
3030 def to_dict(self) -> dict:
Test case

test/inputs/schema/default-values.schema

31 generated files · +2,207 −0
Aschema-cjsondefault / TopLevel.c+81 −0
@@ -0,0 +1,81 @@
1+/**
2+ * TopLevel.c
3+ * This file has been autogenerated using quicktype https://github.com/quicktype/quicktype - DO NOT EDIT
4+ */
5+
6+#include "TopLevel.h"
7+
8+struct TopLevel * cJSON_ParseTopLevel(const char * s) {
9+ struct TopLevel * x = NULL;
10+ if (NULL != s) {
11+ cJSON * j = cJSON_Parse(s);
12+ if (NULL != j) {
13+ x = cJSON_GetTopLevelValue(j);
14+ cJSON_Delete(j);
15+ }
16+ }
17+ return x;
18+}
19+
20+struct TopLevel * cJSON_GetTopLevelValue(const cJSON * j) {
21+ struct TopLevel * x = NULL;
22+ if (NULL != j) {
23+ if (NULL != (x = cJSON_malloc(sizeof(struct TopLevel)))) {
24+ memset(x, 0, sizeof(struct TopLevel));
25+ if (cJSON_HasObjectItem(j, "Greeting")) {
26+ x->greeting = strdup(cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(j, "Greeting")));
27+ }
28+ if (cJSON_HasObjectItem(j, "Name")) {
29+ x->name = strdup(cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(j, "Name")));
30+ }
31+ else {
32+ if (NULL != (x->name = cJSON_malloc(sizeof(char)))) {
33+ x->name[0] = '\0';
34+ }
35+ }
36+ }
37+ }
38+ return x;
39+}
40+
41+cJSON * cJSON_CreateTopLevel(const struct TopLevel * x) {
42+ cJSON * j = NULL;
43+ if (NULL != x) {
44+ if (NULL != (j = cJSON_CreateObject())) {
45+ if (NULL != x->greeting) {
46+ cJSON_AddStringToObject(j, "Greeting", x->greeting);
47+ }
48+ if (NULL != x->name) {
49+ cJSON_AddStringToObject(j, "Name", x->name);
50+ }
51+ else {
52+ cJSON_AddStringToObject(j, "Name", "");
53+ }
54+ }
55+ }
56+ return j;
57+}
58+
59+char * cJSON_PrintTopLevel(const struct TopLevel * x) {
60+ char * s = NULL;
61+ if (NULL != x) {
62+ cJSON * j = cJSON_CreateTopLevel(x);
63+ if (NULL != j) {
64+ s = cJSON_Print(j);
65+ cJSON_Delete(j);
66+ }
67+ }
68+ return s;
69+}
70+
71+void cJSON_DeleteTopLevel(struct TopLevel * x) {
72+ if (NULL != x) {
73+ if (NULL != x->greeting) {
74+ cJSON_free(x->greeting);
75+ }
76+ if (NULL != x->name) {
77+ cJSON_free(x->name);
78+ }
79+ cJSON_free(x);
80+ }
81+}
Aschema-cjsondefault / TopLevel.h+52 −0
@@ -0,0 +1,52 @@
1+/**
2+ * TopLevel.h
3+ * This file has been autogenerated using quicktype https://github.com/quicktype/quicktype - DO NOT EDIT
4+ * This file depends of https://github.com/DaveGamble/cJSON, https://github.com/joelguittet/c-list and https://github.com/joelguittet/c-hashtable
5+ * To parse json data from json string use the following: struct <type> * data = cJSON_Parse<type>(<string>);
6+ * To get json data from cJSON object use the following: struct <type> * data = cJSON_Get<type>Value(<cjson>);
7+ * To get cJSON object from json data use the following: cJSON * cjson = cJSON_Create<type>(<data>);
8+ * To print json string from json data use the following: char * string = cJSON_Print<type>(<data>);
9+ * To delete json data use the following: cJSON_Delete<type>(<data>);
10+ */
11+
12+#ifndef __TOPLEVEL_H__
13+#define __TOPLEVEL_H__
14+
15+#ifdef __cplusplus
16+extern "C" {
17+#endif
18+
19+#include <stdint.h>
20+#include <stdbool.h>
21+#include <stdlib.h>
22+#include <string.h>
23+#include <cJSON.h>
24+#include <hashtable.h>
25+#include <list.h>
26+
27+#ifndef cJSON_Bool
28+#define cJSON_Bool (cJSON_True | cJSON_False)
29+#endif
30+#ifndef cJSON_Map
31+#define cJSON_Map (1 << 16)
32+#endif
33+#ifndef cJSON_Enum
34+#define cJSON_Enum (1 << 17)
35+#endif
36+
37+struct TopLevel {
38+ char * greeting;
39+ char * name;
40+};
41+
42+struct TopLevel * cJSON_ParseTopLevel(const char * s);
43+struct TopLevel * cJSON_GetTopLevelValue(const cJSON * j);
44+cJSON * cJSON_CreateTopLevel(const struct TopLevel * x);
45+char * cJSON_PrintTopLevel(const struct TopLevel * x);
46+void cJSON_DeleteTopLevel(struct TopLevel * x);
47+
48+#ifdef __cplusplus
49+}
50+#endif
51+
52+#endif /* __TOPLEVEL_H__ */
Aschema-cplusplusdefault / quicktype.hpp+125 −0
@@ -0,0 +1,125 @@
1+// To parse this JSON data, first install
2+//
3+// json.hpp https://github.com/nlohmann/json
4+//
5+// Then include this file, and then do
6+//
7+// TopLevel data = nlohmann::json::parse(jsonString);
8+
9+#pragma once
10+
11+#include <optional>
12+#include "json.hpp"
13+
14+#include <optional>
15+#include <stdexcept>
16+#include <regex>
17+
18+#ifndef NLOHMANN_OPT_HELPER
19+#define NLOHMANN_OPT_HELPER
20+namespace nlohmann {
21+ template <typename T>
22+ struct adl_serializer<std::shared_ptr<T>> {
23+ static void to_json(json & j, const std::shared_ptr<T> & opt) {
24+ if (!opt) j = nullptr; else j = *opt;
25+ }
26+
27+ static std::shared_ptr<T> from_json(const json & j) {
28+ if (j.is_null()) return std::shared_ptr<T>(); else return std::make_shared<T>(j.get<T>());
29+ }
30+ };
31+ template <typename T>
32+ struct adl_serializer<std::optional<T>> {
33+ static void to_json(json & j, const std::optional<T> & opt) {
34+ if (!opt) j = nullptr; else j = *opt;
35+ }
36+
37+ static std::optional<T> from_json(const json & j) {
38+ if (j.is_null()) return std::optional<T>(); else return std::make_optional<T>(j.get<T>());
39+ }
40+ };
41+}
42+#endif
43+
44+namespace quicktype {
45+ using nlohmann::json;
46+
47+ #ifndef NLOHMANN_UNTYPED_quicktype_HELPER
48+ #define NLOHMANN_UNTYPED_quicktype_HELPER
49+ inline json get_untyped(const json & j, const char * property) {
50+ if (j.find(property) != j.end()) {
51+ return j.at(property).get<json>();
52+ }
53+ return json();
54+ }
55+
56+ inline json get_untyped(const json & j, std::string property) {
57+ return get_untyped(j, property.data());
58+ }
59+ #endif
60+
61+ #ifndef NLOHMANN_OPTIONAL_quicktype_HELPER
62+ #define NLOHMANN_OPTIONAL_quicktype_HELPER
63+ template <typename T>
64+ inline std::shared_ptr<T> get_heap_optional(const json & j, const char * property) {
65+ auto it = j.find(property);
66+ if (it != j.end() && !it->is_null()) {
67+ return j.at(property).get<std::shared_ptr<T>>();
68+ }
69+ return std::shared_ptr<T>();
70+ }
71+
72+ template <typename T>
73+ inline std::shared_ptr<T> get_heap_optional(const json & j, std::string property) {
74+ return get_heap_optional<T>(j, property.data());
75+ }
76+ template <typename T>
77+ inline std::optional<T> get_stack_optional(const json & j, const char * property) {
78+ auto it = j.find(property);
79+ if (it != j.end() && !it->is_null()) {
80+ return j.at(property).get<std::optional<T>>();
81+ }
82+ return std::optional<T>();
83+ }
84+
85+ template <typename T>
86+ inline std::optional<T> get_stack_optional(const json & j, std::string property) {
87+ return get_stack_optional<T>(j, property.data());
88+ }
89+ #endif
90+
91+ class TopLevel {
92+ public:
93+ TopLevel() = default;
94+ virtual ~TopLevel() = default;
95+
96+ private:
97+ std::optional<std::string> greeting = "World";
98+ std::string name = "Hello";
99+
100+ public:
101+ const std::optional<std::string> & get_greeting() const { return greeting; }
102+ std::optional<std::string> & get_mutable_greeting() { return greeting; }
103+ void set_greeting(const std::optional<std::string> & value) { this->greeting = value; }
104+
105+ const std::string & get_name() const { return name; }
106+ std::string & get_mutable_name() { return name; }
107+ void set_name(const std::string & value) { this->name = value; }
108+ };
109+}
110+
111+namespace quicktype {
112+ void from_json(const json & j, TopLevel & x);
113+ void to_json(json & j, const TopLevel & x);
114+
115+ inline void from_json(const json & j, TopLevel& x) {
116+ x.set_greeting(get_stack_optional<std::string>(j, "Greeting"));
117+ x.set_name(j.at("Name").get<std::string>());
118+ }
119+
120+ inline void to_json(json & j, const TopLevel & x) {
121+ j = json::object();
122+ j["Greeting"] = x.get_greeting();
123+ j["Name"] = x.get_name();
124+ }
125+}
Aschema-csharp-recordsdefault / QuickType.cs+64 −0
@@ -0,0 +1,64 @@
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("Greeting", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
29+ public string? Greeting { get; set; }
30+
31+ [JsonProperty("Name", Required = Required.Always)]
32+ public string Name { get; set; }
33+ }
34+
35+ public partial record TopLevel
36+ {
37+ public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings);
38+ }
39+
40+ public static partial class Serialize
41+ {
42+ public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
43+ }
44+
45+ internal static partial class Converter
46+ {
47+ public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
48+ {
49+ MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
50+ DateParseHandling = DateParseHandling.None,
51+ Converters =
52+ {
53+ new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
54+ },
55+ };
56+ }
57+}
58+#pragma warning restore CS8618
59+#pragma warning restore CS8601
60+#pragma warning restore CS8602
61+#pragma warning restore CS8603
62+#pragma warning restore CS8604
63+#pragma warning restore CS8625
64+#pragma warning restore CS8765
Aschema-csharp-SystemTextJsondefault / QuickType.cs+170 −0
@@ -0,0 +1,170 @@
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+ [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
26+ [JsonPropertyName("Greeting")]
27+ public string? Greeting { get; set; }
28+
29+ [JsonRequired]
30+ [JsonPropertyName("Name")]
31+ public string Name { get; set; }
32+ }
33+
34+ public partial class TopLevel
35+ {
36+ public static TopLevel FromJson(string json) => JsonSerializer.Deserialize<TopLevel>(json, QuickType.Converter.Settings);
37+ }
38+
39+ public static partial class Serialize
40+ {
41+ public static string ToJson(this TopLevel self) => JsonSerializer.Serialize(self, QuickType.Converter.Settings);
42+ }
43+
44+ internal static partial class Converter
45+ {
46+ public static readonly JsonSerializerOptions Settings = new(JsonSerializerDefaults.General)
47+ {
48+ Converters =
49+ {
50+ new DateOnlyConverter(),
51+ new TimeOnlyConverter(),
52+ IsoDateTimeOffsetConverter.Singleton
53+ },
54+ };
55+ }
56+
57+ public class DateOnlyConverter : JsonConverter<DateOnly>
58+ {
59+ private readonly string serializationFormat;
60+ public DateOnlyConverter() : this(null) { }
61+
62+ public DateOnlyConverter(string? serializationFormat)
63+ {
64+ this.serializationFormat = serializationFormat ?? "yyyy-MM-dd";
65+ }
66+
67+ public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
68+ {
69+ var value = reader.GetString();
70+ return DateOnly.Parse(value!);
71+ }
72+
73+ public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
74+ => writer.WriteStringValue(value.ToString(serializationFormat));
75+ }
76+
77+ public class TimeOnlyConverter : JsonConverter<TimeOnly>
78+ {
79+ private readonly string serializationFormat;
80+
81+ public TimeOnlyConverter() : this(null) { }
82+
83+ public TimeOnlyConverter(string? serializationFormat)
84+ {
85+ this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff";
86+ }
87+
88+ public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
89+ {
90+ var value = reader.GetString();
91+ return TimeOnly.Parse(value!);
92+ }
93+
94+ public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options)
95+ => writer.WriteStringValue(value.ToString(serializationFormat));
96+ }
97+
98+ internal class IsoDateTimeOffsetConverter : JsonConverter<DateTimeOffset>
99+ {
100+ public override bool CanConvert(Type t) => t == typeof(DateTimeOffset);
101+
102+ private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
103+
104+ private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind;
105+ private string? _dateTimeFormat;
106+ private CultureInfo? _culture;
107+
108+ public DateTimeStyles DateTimeStyles
109+ {
110+ get => _dateTimeStyles;
111+ set => _dateTimeStyles = value;
112+ }
113+
114+ public string? DateTimeFormat
115+ {
116+ get => _dateTimeFormat ?? string.Empty;
117+ set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value;
118+ }
119+
120+ public CultureInfo Culture
121+ {
122+ get => _culture ?? CultureInfo.CurrentCulture;
123+ set => _culture = value;
124+ }
125+
126+ public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
127+ {
128+ string text;
129+
130+
131+ if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
132+ || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
133+ {
134+ value = value.ToUniversalTime();
135+ }
136+
137+ text = value.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
138+
139+ writer.WriteStringValue(text);
140+ }
141+
142+ public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
143+ {
144+ string? dateText = reader.GetString();
145+
146+ if (string.IsNullOrEmpty(dateText) == false)
147+ {
148+ if (!string.IsNullOrEmpty(_dateTimeFormat))
149+ {
150+ return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
151+ }
152+ else
153+ {
154+ return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles);
155+ }
156+ }
157+ else
158+ {
159+ return default(DateTimeOffset);
160+ }
161+ }
162+
163+
164+ public static readonly IsoDateTimeOffsetConverter Singleton = new IsoDateTimeOffsetConverter();
165+ }
166+}
167+#pragma warning restore CS8618
168+#pragma warning restore CS8601
169+#pragma warning restore CS8602
170+#pragma warning restore CS8603
Aschema-csharpdefault / QuickType.cs+64 −0
@@ -0,0 +1,64 @@
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("Greeting", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
29+ public string? Greeting { get; set; }
30+
31+ [JsonProperty("Name", Required = Required.Always)]
32+ public string Name { get; set; }
33+ }
34+
35+ public partial class TopLevel
36+ {
37+ public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings);
38+ }
39+
40+ public static partial class Serialize
41+ {
42+ public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
43+ }
44+
45+ internal static partial class Converter
46+ {
47+ public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
48+ {
49+ MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
50+ DateParseHandling = DateParseHandling.None,
51+ Converters =
52+ {
53+ new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
54+ },
55+ };
56+ }
57+}
58+#pragma warning restore CS8618
59+#pragma warning restore CS8601
60+#pragma warning restore CS8602
61+#pragma warning restore CS8603
62+#pragma warning restore CS8604
63+#pragma warning restore CS8625
64+#pragma warning restore CS8765
Aschema-dartdefault / TopLevel.dart+29 −0
@@ -0,0 +1,29 @@
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 String? greeting;
13+ final String name;
14+
15+ TopLevel({
16+ this.greeting,
17+ required this.name,
18+ });
19+
20+ factory TopLevel.fromJson(Map<String, dynamic> json) => TopLevel(
21+ greeting: json["Greeting"],
22+ name: json["Name"],
23+ );
24+
25+ Map<String, dynamic> toJson() => {
26+ "Greeting": greeting,
27+ "Name": name,
28+ };
29+}
Aschema-elmdefault / QuickType.elm+54 −0
@@ -0,0 +1,54 @@
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+ )
19+
20+import Json.Decode as Jdec
21+import Json.Decode.Pipeline as Jpipe
22+import Json.Encode as Jenc
23+import Dict exposing (Dict)
24+
25+type alias QuickType =
26+ { greeting : Maybe String
27+ , name : String
28+ }
29+
30+-- decoders and encoders
31+
32+quickTypeToString : QuickType -> String
33+quickTypeToString r = Jenc.encode 0 (encodeQuickType r)
34+
35+quickType : Jdec.Decoder QuickType
36+quickType =
37+ Jdec.succeed QuickType
38+ |> Jpipe.optional "Greeting" (Jdec.nullable Jdec.string) Nothing
39+ |> Jpipe.required "Name" Jdec.string
40+
41+encodeQuickType : QuickType -> Jenc.Value
42+encodeQuickType x =
43+ Jenc.object
44+ [ ("Greeting", makeNullableEncoder Jenc.string x.greeting)
45+ , ("Name", Jenc.string x.name)
46+ ]
47+
48+--- encoder helpers
49+
50+makeNullableEncoder : (a -> Jenc.Value) -> Maybe a -> Jenc.Value
51+makeNullableEncoder f m =
52+ case m of
53+ Just x -> f x
54+ Nothing -> Jenc.null
Aschema-flowdefault / TopLevel.js+190 −0
@@ -0,0 +1,190 @@
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+ Greeting?: string;
14+ Name: string;
15+};
16+
17+// Converts JSON strings to/from your types
18+// and asserts the results of JSON.parse at runtime
19+function toTopLevel(json: string): TopLevel {
20+ return cast(JSON.parse(json), r("TopLevel"));
21+}
22+
23+function topLevelToJson(value: TopLevel): string {
24+ return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
25+}
26+
27+function invalidValue(typ: any, val: any, key: any, parent: any = '') {
28+ const prettyTyp = prettyTypeName(typ);
29+ const parentText = parent ? ` on ${parent}` : '';
30+ const keyText = key ? ` for key "${key}"` : '';
31+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
32+}
33+
34+function prettyTypeName(typ: any): string {
35+ if (Array.isArray(typ)) {
36+ if (typ.length === 2 && typ[0] === undefined) {
37+ return `an optional ${prettyTypeName(typ[1])}`;
38+ } else {
39+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
40+ }
41+ } else if (typeof typ === "object" && typ.literal !== undefined) {
42+ return typ.literal;
43+ } else {
44+ return typeof typ;
45+ }
46+}
47+
48+function jsonToJSProps(typ: any): any {
49+ if (typ.jsonToJS === undefined) {
50+ const map: any = {};
51+ typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
52+ typ.jsonToJS = map;
53+ }
54+ return typ.jsonToJS;
55+}
56+
57+function jsToJSONProps(typ: any): any {
58+ if (typ.jsToJSON === undefined) {
59+ const map: any = {};
60+ typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
61+ typ.jsToJSON = map;
62+ }
63+ return typ.jsToJSON;
64+}
65+
66+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
67+ function transformPrimitive(typ: string, val: any): any {
68+ if (typeof typ === typeof val) return val;
69+ return invalidValue(typ, val, key, parent);
70+ }
71+
72+ function transformUnion(typs: any[], val: any): any {
73+ // val must validate against one typ in typs
74+ const l = typs.length;
75+ for (let i = 0; i < l; i++) {
76+ const typ = typs[i];
77+ try {
78+ return transform(val, typ, getProps);
79+ } catch (_) {}
80+ }
81+ return invalidValue(typs, val, key, parent);
82+ }
83+
84+ function transformEnum(cases: string[], val: any): any {
85+ if (cases.indexOf(val) !== -1) return val;
86+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
87+ }
88+
89+ function transformArray(typ: any, val: any): any {
90+ // val must be an array with no invalid elements
91+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
92+ return val.map(el => transform(el, typ, getProps));
93+ }
94+
95+ function transformDate(val: any): any {
96+ if (val === null) {
97+ return null;
98+ }
99+ const d = new Date(val);
100+ if (isNaN(d.valueOf())) {
101+ return invalidValue(l("Date"), val, key, parent);
102+ }
103+ return d;
104+ }
105+
106+ function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
107+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
108+ return invalidValue(l(ref || "object"), val, key, parent);
109+ }
110+ const result: any = {};
111+ Object.getOwnPropertyNames(props).forEach(key => {
112+ const prop = props[key];
113+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
114+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
115+ });
116+ Object.getOwnPropertyNames(val).forEach(key => {
117+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
118+ result[key] = transform(val[key], additional, getProps, key, ref);
119+ }
120+ });
121+ return result;
122+ }
123+
124+ if (typ === "any") return val;
125+ if (typ === null) {
126+ if (val === null) return val;
127+ return invalidValue(typ, val, key, parent);
128+ }
129+ if (typ === false) return invalidValue(typ, val, key, parent);
130+ let ref: any = undefined;
131+ while (typeof typ === "object" && typ.ref !== undefined) {
132+ ref = typ.ref;
133+ typ = typeMap[typ.ref];
134+ }
135+ if (Array.isArray(typ)) return transformEnum(typ, val);
136+ if (typeof typ === "object") {
137+ return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
138+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
139+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
140+ : invalidValue(typ, val, key, parent);
141+ }
142+ // Numbers can be parsed by Date but shouldn't be.
143+ if (typ === Date && typeof val !== "number") return transformDate(val);
144+ return transformPrimitive(typ, val);
145+}
146+
147+function cast<T>(val: any, typ: any): T {
148+ return transform(val, typ, jsonToJSProps);
149+}
150+
151+function uncast<T>(val: T, typ: any): any {
152+ return transform(val, typ, jsToJSONProps);
153+}
154+
155+function l(typ: any) {
156+ return { literal: typ };
157+}
158+
159+function a(typ: any) {
160+ return { arrayItems: typ };
161+}
162+
163+function u(...typs: any[]) {
164+ return { unionMembers: typs };
165+}
166+
167+function o(props: any[], additional: any) {
168+ return { props, additional };
169+}
170+
171+function m(additional: any) {
172+ const props: any[] = [];
173+ return { props, additional };
174+}
175+
176+function r(name: string) {
177+ return { ref: name };
178+}
179+
180+const typeMap: any = {
181+ "TopLevel": o([
182+ { json: "Greeting", js: "Greeting", typ: u(undefined, "") },
183+ { json: "Name", js: "Name", typ: "" },
184+ ], false),
185+};
186+
187+module.exports = {
188+ "topLevelToJson": topLevelToJson,
189+ "toTopLevel": toTopLevel,
190+};
Aschema-golangdefault / quicktype.go+24 −0
@@ -0,0 +1,24 @@
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+ Greeting *string `json:"Greeting,omitempty"`
23+ Name string `json:"Name"`
24+}
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 / 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 String greeting;
7+ private String name;
8+
9+ @JsonProperty("Greeting")
10+ public String getGreeting() { return greeting; }
11+ @JsonProperty("Greeting")
12+ public void setGreeting(String value) { this.greeting = value; }
13+
14+ @JsonProperty("Name")
15+ public String getName() { return name; }
16+ @JsonProperty("Name")
17+ public void setName(String value) { this.name = 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 / 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 String greeting;
7+ private String name;
8+
9+ @JsonProperty("Greeting")
10+ public String getGreeting() { return greeting; }
11+ @JsonProperty("Greeting")
12+ public void setGreeting(String value) { this.greeting = value; }
13+
14+ @JsonProperty("Name")
15+ public String getName() { return name; }
16+ @JsonProperty("Name")
17+ public void setName(String value) { this.name = 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 / 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 String greeting;
7+ private String name;
8+
9+ @JsonProperty("Greeting")
10+ public String getGreeting() { return greeting; }
11+ @JsonProperty("Greeting")
12+ public void setGreeting(String value) { this.greeting = value; }
13+
14+ @JsonProperty("Name")
15+ public String getName() { return name; }
16+ @JsonProperty("Name")
17+ public void setName(String value) { this.name = value; }
18+}
Aschema-javascriptdefault / TopLevel.js+183 −0
@@ -0,0 +1,183 @@
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: "Greeting", js: "Greeting", typ: u(undefined, "") },
176+ { json: "Name", js: "Name", typ: "" },
177+ ], false),
178+};
179+
180+module.exports = {
181+ "topLevelToJson": topLevelToJson,
182+ "toTopLevel": toTopLevel,
183+};
Aschema-kotlin-jacksondefault / TopLevel.kt+33 −0
@@ -0,0 +1,33 @@
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("Greeting")@field:JsonProperty("Greeting")
23+ val greeting: String? = null,
24+
25+ @get:JsonProperty("Name", required=true)@field:JsonProperty("Name", required=true)
26+ val name: String
27+) {
28+ fun toJson() = mapper.writeValueAsString(this)
29+
30+ companion object {
31+ fun fromJson(json: String) = mapper.readValue<TopLevel>(json)
32+ }
33+}
Aschema-kotlindefault / TopLevel.kt+23 −0
@@ -0,0 +1,23 @@
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+ @Json(name = "Greeting")
13+ val greeting: String? = null,
14+
15+ @Json(name = "Name")
16+ val name: String
17+) {
18+ public fun toJson() = klaxon.toJsonString(this)
19+
20+ companion object {
21+ public fun fromJson(json: String) = klaxon.parse<TopLevel>(json)
22+ }
23+}
Aschema-kotlinxdefault / TopLevel.kt+20 −0
@@ -0,0 +1,20 @@
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+ @SerialName("Greeting")
16+ val greeting: String? = null,
17+
18+ @SerialName("Name")
19+ val name: String
20+)
Aschema-phpdefault / TopLevel.php+164 −0
@@ -0,0 +1,164 @@
1+<?php
2+declare(strict_types=1);
3+
4+// This is an autogenerated file:TopLevel
5+
6+class TopLevel {
7+ private ?string $greeting; // json:Greeting Optional
8+ private string $name; // json:Name Required
9+
10+ /**
11+ * @param string|null $greeting
12+ * @param string $name
13+ */
14+ public function __construct(?string $greeting, string $name) {
15+ $this->greeting = $greeting;
16+ $this->name = $name;
17+ }
18+
19+ /**
20+ * @param ?string $value
21+ * @throws Exception
22+ * @return ?string
23+ */
24+ public static function fromGreeting(?string $value): ?string {
25+ if (!is_null($value)) {
26+ return $value; /*string*/
27+ } else {
28+ return null;
29+ }
30+ }
31+
32+ /**
33+ * @throws Exception
34+ * @return ?string
35+ */
36+ public function toGreeting(): ?string {
37+ if (TopLevel::validateGreeting($this->greeting)) {
38+ if (!is_null($this->greeting)) {
39+ return $this->greeting; /*string*/
40+ } else {
41+ return null;
42+ }
43+ }
44+ throw new Exception('never get to this TopLevel::greeting');
45+ }
46+
47+ /**
48+ * @param string|null
49+ * @return bool
50+ * @throws Exception
51+ */
52+ public static function validateGreeting(?string $value): bool {
53+ if (!is_null($value)) {
54+ }
55+ return true;
56+ }
57+
58+ /**
59+ * @throws Exception
60+ * @return ?string
61+ */
62+ public function getGreeting(): ?string {
63+ if (TopLevel::validateGreeting($this->greeting)) {
64+ return $this->greeting;
65+ }
66+ throw new Exception('never get to getGreeting TopLevel::greeting');
67+ }
68+
69+ /**
70+ * @return ?string
71+ */
72+ public static function sampleGreeting(): ?string {
73+ return 'TopLevel::greeting::31'; /*31:greeting*/
74+ }
75+
76+ /**
77+ * @param string $value
78+ * @throws Exception
79+ * @return string
80+ */
81+ public static function fromName(string $value): string {
82+ return $value; /*string*/
83+ }
84+
85+ /**
86+ * @throws Exception
87+ * @return string
88+ */
89+ public function toName(): string {
90+ if (TopLevel::validateName($this->name)) {
91+ return $this->name; /*string*/
92+ }
93+ throw new Exception('never get to this TopLevel::name');
94+ }
95+
96+ /**
97+ * @param string
98+ * @return bool
99+ * @throws Exception
100+ */
101+ public static function validateName(string $value): bool {
102+ return true;
103+ }
104+
105+ /**
106+ * @throws Exception
107+ * @return string
108+ */
109+ public function getName(): string {
110+ if (TopLevel::validateName($this->name)) {
111+ return $this->name;
112+ }
113+ throw new Exception('never get to getName TopLevel::name');
114+ }
115+
116+ /**
117+ * @return string
118+ */
119+ public static function sampleName(): string {
120+ return 'TopLevel::name::32'; /*32:name*/
121+ }
122+
123+ /**
124+ * @throws Exception
125+ * @return bool
126+ */
127+ public function validate(): bool {
128+ return TopLevel::validateGreeting($this->greeting)
129+ || TopLevel::validateName($this->name);
130+ }
131+
132+ /**
133+ * @return stdClass
134+ * @throws Exception
135+ */
136+ public function to(): stdClass {
137+ $out = new stdClass();
138+ $out->{'Greeting'} = $this->toGreeting();
139+ $out->{'Name'} = $this->toName();
140+ return $out;
141+ }
142+
143+ /**
144+ * @param stdClass $obj
145+ * @return TopLevel
146+ * @throws Exception
147+ */
148+ public static function from(stdClass $obj): TopLevel {
149+ return new TopLevel(
150+ TopLevel::fromGreeting($obj->{'Greeting'})
151+ ,TopLevel::fromName($obj->{'Name'})
152+ );
153+ }
154+
155+ /**
156+ * @return TopLevel
157+ */
158+ public static function sample(): TopLevel {
159+ return new TopLevel(
160+ TopLevel::sampleGreeting()
161+ ,TopLevel::sampleName()
162+ );
163+ }
164+}
Aschema-pikedefault / TopLevel.pmod+36 −0
@@ -0,0 +1,36 @@
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+ mixed|string greeting; // json: "Greeting"
17+ string name; // json: "Name"
18+
19+ string encode_json() {
20+ mapping(string:mixed) json = ([
21+ "Greeting" : greeting,
22+ "Name" : name,
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.greeting = json["Greeting"];
33+ retval.name = json["Name"];
34+
35+ return retval;
36+}
Aschema-pythondefault / quicktype.py+57 −0
@@ -0,0 +1,57 @@
1+from dataclasses import dataclass
2+from typing import Any, TypeVar, Type, cast
3+
4+
5+T = TypeVar("T")
6+
7+
8+def from_str(x: Any) -> str:
9+ assert isinstance(x, str)
10+ return x
11+
12+
13+def from_none(x: Any) -> Any:
14+ assert x is None
15+ return x
16+
17+
18+def from_union(fs, x):
19+ for f in fs:
20+ try:
21+ return f(x)
22+ except:
23+ pass
24+ assert False
25+
26+
27+def to_class(c: Type[T], x: Any) -> dict:
28+ assert isinstance(x, c)
29+ return cast(Any, x).to_dict()
30+
31+
32+@dataclass
33+class TopLevel:
34+ greeting: str | None = "World"
35+ name: str = "Hello"
36+
37+ @staticmethod
38+ def from_dict(obj: Any) -> 'TopLevel':
39+ assert isinstance(obj, dict)
40+ greeting = from_union([from_str, from_none], obj.get("Greeting", "World"))
41+ name = from_str(obj.get("Name", "Hello"))
42+ return TopLevel(greeting, name)
43+
44+ def to_dict(self) -> dict:
45+ result: dict = {}
46+ if self.greeting is not None:
47+ result["Greeting"] = from_union([from_str, from_none], self.greeting)
48+ result["Name"] = from_str(self.name)
49+ return result
50+
51+
52+def top_level_from_dict(s: Any) -> TopLevel:
53+ return TopLevel.from_dict(s)
54+
55+
56+def top_level_to_dict(x: TopLevel) -> Any:
57+ return to_class(TopLevel, x)
Aschema-rubydefault / TopLevel.rb+48 −0
@@ -0,0 +1,48 @@
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.greeting
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 TopLevel < Dry::Struct
23+ attribute :greeting, Types::String.optional
24+ attribute :top_level_name, Types::String
25+
26+ def self.from_dynamic!(d)
27+ d = Types::Hash[d]
28+ new(
29+ greeting: d["Greeting"],
30+ top_level_name: d.fetch("Name"),
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+ "Greeting" => greeting,
41+ "Name" => top_level_name,
42+ }
43+ end
44+
45+ def to_json(options = nil)
46+ JSON.generate(to_dynamic, options)
47+ end
48+end
Aschema-rustdefault / module_under_test.rs+22 −0
@@ -0,0 +1,22 @@
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+#[serde(rename_all = "PascalCase")]
18+pub struct TopLevel {
19+ pub greeting: Option<String>,
20+
21+ pub name: String,
22+}
Aschema-scala3-upickledefault / TopLevel.scala+71 −0
@@ -0,0 +1,71 @@
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 Greeting : Option[String] = None,
70+ val Name : String
71+) derives OptionPickler.ReadWriter
Aschema-scala3default / TopLevel.scala+13 −0
@@ -0,0 +1,13 @@
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 Greeting : Option[String] = None,
12+ val Name : String
13+) derives Encoder.AsObject, Decoder
Aschema-schemadefault / TopLevel.schema+24 −0
@@ -0,0 +1,24 @@
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+ "Greeting": {
10+ "type": "string",
11+ "default": "World"
12+ },
13+ "Name": {
14+ "type": "string",
15+ "default": "Hello"
16+ }
17+ },
18+ "required": [
19+ "Name"
20+ ],
21+ "title": "TopLevel"
22+ }
23+ }
24+}
Aschema-swiftdefault / quicktype.swift+90 −0
@@ -0,0 +1,90 @@
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 greeting: String?
11+ let name: String
12+
13+ enum CodingKeys: String, CodingKey {
14+ case greeting = "Greeting"
15+ case name = "Name"
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+ greeting: String?? = nil,
39+ name: String? = nil
40+ ) -> TopLevel {
41+ return TopLevel(
42+ greeting: greeting ?? self.greeting,
43+ name: name ?? self.name
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: - Helper functions for creating encoders and decoders
57+
58+func newJSONDecoder() -> JSONDecoder {
59+ let decoder = JSONDecoder()
60+ decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in
61+ let container = try decoder.singleValueContainer()
62+ let dateStr = try container.decode(String.self)
63+
64+ let formatter = DateFormatter()
65+ formatter.calendar = Calendar(identifier: .iso8601)
66+ formatter.locale = Locale(identifier: "en_US_POSIX")
67+ formatter.timeZone = TimeZone(secondsFromGMT: 0)
68+ formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
69+ if let date = formatter.date(from: dateStr) {
70+ return date
71+ }
72+ formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
73+ if let date = formatter.date(from: dateStr) {
74+ return date
75+ }
76+ throw DecodingError.typeMismatch(Date.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not decode date"))
77+ })
78+ return decoder
79+}
80+
81+func newJSONEncoder() -> JSONEncoder {
82+ let encoder = JSONEncoder()
83+ let formatter = DateFormatter()
84+ formatter.calendar = Calendar(identifier: .iso8601)
85+ formatter.locale = Locale(identifier: "en_US_POSIX")
86+ formatter.timeZone = TimeZone(secondsFromGMT: 0)
87+ formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
88+ encoder.dateEncodingStrategy = .formatted(formatter)
89+ return encoder
90+}
Aschema-typescript-zoddefault / TopLevel.ts+8 −0
@@ -0,0 +1,8 @@
1+import * as z from "zod";
2+
3+
4+export const TopLevelSchema = z.object({
5+ "Greeting": z.string().optional(),
6+ "Name": z.string(),
7+});
8+export type TopLevel = z.infer<typeof TopLevelSchema>;
Aschema-typescriptdefault / TopLevel.ts+185 −0
@@ -0,0 +1,185 @@
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+ Greeting?: string;
12+ Name: string;
13+}
14+
15+// Converts JSON strings to/from your types
16+// and asserts the results of JSON.parse at runtime
17+export class Convert {
18+ public static toTopLevel(json: string): TopLevel {
19+ return cast(JSON.parse(json), r("TopLevel"));
20+ }
21+
22+ public static topLevelToJson(value: TopLevel): string {
23+ return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
24+ }
25+}
26+
27+function invalidValue(typ: any, val: any, key: any, parent: any = ''): never {
28+ const prettyTyp = prettyTypeName(typ);
29+ const parentText = parent ? ` on ${parent}` : '';
30+ const keyText = key ? ` for key "${key}"` : '';
31+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
32+}
33+
34+function prettyTypeName(typ: any): string {
35+ if (Array.isArray(typ)) {
36+ if (typ.length === 2 && typ[0] === undefined) {
37+ return `an optional ${prettyTypeName(typ[1])}`;
38+ } else {
39+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
40+ }
41+ } else if (typeof typ === "object" && typ.literal !== undefined) {
42+ return typ.literal;
43+ } else {
44+ return typeof typ;
45+ }
46+}
47+
48+function jsonToJSProps(typ: any): any {
49+ if (typ.jsonToJS === undefined) {
50+ const map: any = {};
51+ typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
52+ typ.jsonToJS = map;
53+ }
54+ return typ.jsonToJS;
55+}
56+
57+function jsToJSONProps(typ: any): any {
58+ if (typ.jsToJSON === undefined) {
59+ const map: any = {};
60+ typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
61+ typ.jsToJSON = map;
62+ }
63+ return typ.jsToJSON;
64+}
65+
66+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
67+ function transformPrimitive(typ: string, val: any): any {
68+ if (typeof typ === typeof val) return val;
69+ return invalidValue(typ, val, key, parent);
70+ }
71+
72+ function transformUnion(typs: any[], val: any): any {
73+ // val must validate against one typ in typs
74+ const l = typs.length;
75+ for (let i = 0; i < l; i++) {
76+ const typ = typs[i];
77+ try {
78+ return transform(val, typ, getProps);
79+ } catch (_) {}
80+ }
81+ return invalidValue(typs, val, key, parent);
82+ }
83+
84+ function transformEnum(cases: string[], val: any): any {
85+ if (cases.indexOf(val) !== -1) return val;
86+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
87+ }
88+
89+ function transformArray(typ: any, val: any): any {
90+ // val must be an array with no invalid elements
91+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
92+ return val.map(el => transform(el, typ, getProps));
93+ }
94+
95+ function transformDate(val: any): any {
96+ if (val === null) {
97+ return null;
98+ }
99+ const d = new Date(val);
100+ if (isNaN(d.valueOf())) {
101+ return invalidValue(l("Date"), val, key, parent);
102+ }
103+ return d;
104+ }
105+
106+ function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
107+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
108+ return invalidValue(l(ref || "object"), val, key, parent);
109+ }
110+ const result: any = {};
111+ Object.getOwnPropertyNames(props).forEach(key => {
112+ const prop = props[key];
113+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
114+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
115+ });
116+ Object.getOwnPropertyNames(val).forEach(key => {
117+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
118+ result[key] = transform(val[key], additional, getProps, key, ref);
119+ }
120+ });
121+ return result;
122+ }
123+
124+ if (typ === "any") return val;
125+ if (typ === null) {
126+ if (val === null) return val;
127+ return invalidValue(typ, val, key, parent);
128+ }
129+ if (typ === false) return invalidValue(typ, val, key, parent);
130+ let ref: any = undefined;
131+ while (typeof typ === "object" && typ.ref !== undefined) {
132+ ref = typ.ref;
133+ typ = typeMap[typ.ref];
134+ }
135+ if (Array.isArray(typ)) return transformEnum(typ, val);
136+ if (typeof typ === "object") {
137+ return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
138+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
139+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
140+ : invalidValue(typ, val, key, parent);
141+ }
142+ // Numbers can be parsed by Date but shouldn't be.
143+ if (typ === Date && typeof val !== "number") return transformDate(val);
144+ return transformPrimitive(typ, val);
145+}
146+
147+function cast<T>(val: any, typ: any): T {
148+ return transform(val, typ, jsonToJSProps);
149+}
150+
151+function uncast<T>(val: T, typ: any): any {
152+ return transform(val, typ, jsToJSONProps);
153+}
154+
155+function l(typ: any) {
156+ return { literal: typ };
157+}
158+
159+function a(typ: any) {
160+ return { arrayItems: typ };
161+}
162+
163+function u(...typs: any[]) {
164+ return { unionMembers: typs };
165+}
166+
167+function o(props: any[], additional: any) {
168+ return { props, additional };
169+}
170+
171+function m(additional: any) {
172+ const props: any[] = [];
173+ return { props, additional };
174+}
175+
176+function r(name: string) {
177+ return { ref: name };
178+}
179+
180+const typeMap: any = {
181+ "TopLevel": o([
182+ { json: "Greeting", js: "Greeting", typ: u(undefined, "") },
183+ { json: "Name", js: "Name", typ: "" },
184+ ], false),
185+};
No generated files match these filters.