Generated-output differences

quicktype output changed between the PR base and tested PR merge revisions.
← Back to the pull request
1test cases
42files differ
0modified
42new
0deleted
2,843changed lines
+2,843 −0insertions / deletions
Base 1c4cad7f1ba262f3587ab684ce67a0df96b6d285 · PR merge 7441ac7feb31380b6e4f5f64333ad13fda4630d9 · Head 23d49f3d20166850776d5be291ec80bf0124b57f · raw patch
Test case

test/inputs/schema/single-value-enum.schema

42 generated files · +2,843 −0
Aschema-cjsondefault / TopLevel.c+78 −0
@@ -0,0 +1,78 @@
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+enum Kind cJSON_GetKindValue(const cJSON * j) {
9+ enum Kind x = 0;
10+ if (NULL != j) {
11+ if (!strcmp(cJSON_GetStringValue(j), "only")) x = KIND_ONLY;
12+ }
13+ return x;
14+}
15+
16+cJSON * cJSON_CreateKind(const enum Kind x) {
17+ cJSON * j = NULL;
18+ switch (x) {
19+ case KIND_ONLY: j = cJSON_CreateString("only"); break;
20+ }
21+ return j;
22+}
23+
24+struct TopLevel * cJSON_ParseTopLevel(const char * s) {
25+ struct TopLevel * x = NULL;
26+ if (NULL != s) {
27+ cJSON * j = cJSON_Parse(s);
28+ if (NULL != j) {
29+ x = cJSON_GetTopLevelValue(j);
30+ cJSON_Delete(j);
31+ }
32+ }
33+ return x;
34+}
35+
36+struct TopLevel * cJSON_GetTopLevelValue(const cJSON * j) {
37+ struct TopLevel * x = NULL;
38+ if (NULL != j) {
39+ if (NULL != (x = cJSON_malloc(sizeof(struct TopLevel)))) {
40+ memset(x, 0, sizeof(struct TopLevel));
41+ if (!cJSON_HasObjectItem(j, "kind")) { cJSON_DeleteTopLevel(x); return NULL; }
42+ if (cJSON_HasObjectItem(j, "kind")) {
43+ if (!cJSON_IsString(cJSON_GetObjectItemCaseSensitive(j, "kind"))) { cJSON_DeleteTopLevel(x); return NULL; }
44+ if (!cJSON_IsString(cJSON_GetObjectItemCaseSensitive(j, "kind")) || 0 == cJSON_GetKindValue(cJSON_GetObjectItemCaseSensitive(j, "kind"))) { cJSON_DeleteTopLevel(x); return NULL; }
45+ x->kind = cJSON_GetKindValue(cJSON_GetObjectItemCaseSensitive(j, "kind"));
46+ }
47+ }
48+ }
49+ return x;
50+}
51+
52+cJSON * cJSON_CreateTopLevel(const struct TopLevel * x) {
53+ cJSON * j = NULL;
54+ if (NULL != x) {
55+ if (NULL != (j = cJSON_CreateObject())) {
56+ cJSON_AddItemToObject(j, "kind", cJSON_CreateKind(x->kind));
57+ }
58+ }
59+ return j;
60+}
61+
62+char * cJSON_PrintTopLevel(const struct TopLevel * x) {
63+ char * s = NULL;
64+ if (NULL != x) {
65+ cJSON * j = cJSON_CreateTopLevel(x);
66+ if (NULL != j) {
67+ s = cJSON_Print(j);
68+ cJSON_Delete(j);
69+ }
70+ }
71+ return s;
72+}
73+
74+void cJSON_DeleteTopLevel(struct TopLevel * x) {
75+ if (NULL != x) {
76+ cJSON_free(x);
77+ }
78+}
Aschema-cjsondefault / TopLevel.h+59 −0
@@ -0,0 +1,59 @@
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 <regex.h>
24+#include <cJSON.h>
25+#include <hashtable.h>
26+#include <list.h>
27+
28+#ifndef cJSON_Bool
29+#define cJSON_Bool (cJSON_True | cJSON_False)
30+#endif
31+#ifndef cJSON_Map
32+#define cJSON_Map (1 << 16)
33+#endif
34+#ifndef cJSON_Enum
35+#define cJSON_Enum (1 << 17)
36+#endif
37+
38+enum Kind {
39+ KIND_ONLY = 1,
40+};
41+
42+struct TopLevel {
43+ enum Kind kind;
44+};
45+
46+enum Kind cJSON_GetKindValue(const cJSON * j);
47+cJSON * cJSON_CreateKind(const enum Kind x);
48+
49+struct TopLevel * cJSON_ParseTopLevel(const char * s);
50+struct TopLevel * cJSON_GetTopLevelValue(const cJSON * j);
51+cJSON * cJSON_CreateTopLevel(const struct TopLevel * x);
52+char * cJSON_PrintTopLevel(const struct TopLevel * x);
53+void cJSON_DeleteTopLevel(struct TopLevel * x);
54+
55+#ifdef __cplusplus
56+}
57+#endif
58+
59+#endif /* __TOPLEVEL_H__ */
Aschema-cplusplusdefault / quicktype.hpp+79 −0
@@ -0,0 +1,79 @@
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+ enum class Kind : int { ONLY };
35+
36+ class TopLevel {
37+ public:
38+ TopLevel() = default;
39+ virtual ~TopLevel() = default;
40+
41+ private:
42+ Kind kind;
43+
44+ public:
45+ const Kind & get_kind() const { return kind; }
46+ Kind & get_mutable_kind() { return kind; }
47+ void set_kind(const Kind & value) { this->kind = value; }
48+ };
49+}
50+
51+namespace quicktype {
52+ void from_json(const json & j, TopLevel & x);
53+ void to_json(json & j, const TopLevel & x);
54+
55+ void from_json(const json & j, Kind & x);
56+ void to_json(json & j, const Kind & x);
57+
58+ inline void from_json(const json & j, TopLevel& x) {
59+ if (!j.is_object()) throw std::runtime_error("Expected object");
60+ x.set_kind(j.at("kind").get<Kind>());
61+ }
62+
63+ inline void to_json(json & j, const TopLevel & x) {
64+ j = json::object();
65+ j["kind"] = x.get_kind();
66+ }
67+
68+ inline void from_json(const json & j, Kind & x) {
69+ if (j == "only") x = Kind::ONLY;
70+ else { throw std::runtime_error("Cannot deserialize to enumeration \"Kind\""); }
71+ }
72+
73+ inline void to_json(json & j, const Kind & x) {
74+ switch (x) {
75+ case Kind::ONLY: j = "only"; break;
76+ default: throw std::runtime_error("Unexpected value in enumeration \"Kind\": " + std::to_string(static_cast<int>(x)));
77+ }
78+ }
79+}
Aschema-crystaldefault / TopLevel.cr+7 −0
@@ -0,0 +1,7 @@
1+require "json"
2+
3+class TopLevel
4+ include JSON::Serializable
5+
6+ property kind : String
7+end
Aschema-csharp-recordsdefault / QuickType.cs+98 −0
@@ -0,0 +1,98 @@
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("kind", Required = Required.Always)]
29+ public Kind Kind { get; set; }
30+ }
31+
32+ public enum Kind { Only };
33+
34+ public partial record TopLevel
35+ {
36+ public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings);
37+ }
38+
39+ public static partial class Serialize
40+ {
41+ public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
42+ }
43+
44+ internal static partial class Converter
45+ {
46+ public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
47+ {
48+ MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
49+ DateParseHandling = DateParseHandling.None,
50+ Converters =
51+ {
52+ KindConverter.Singleton,
53+ new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
54+ },
55+ };
56+ }
57+
58+ internal class KindConverter : JsonConverter
59+ {
60+ public override bool CanConvert(Type t) => t == typeof(Kind) || t == typeof(Kind?);
61+
62+ public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
63+ {
64+ if (reader.TokenType == JsonToken.Null) return null;
65+ var value = serializer.Deserialize<string>(reader);
66+ if (value == "only")
67+ {
68+ return Kind.Only;
69+ }
70+ throw new Exception("Cannot unmarshal type Kind");
71+ }
72+
73+ public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
74+ {
75+ if (untypedValue == null)
76+ {
77+ serializer.Serialize(writer, null);
78+ return;
79+ }
80+ var value = (Kind)untypedValue;
81+ if (value == Kind.Only)
82+ {
83+ serializer.Serialize(writer, "only");
84+ return;
85+ }
86+ throw new Exception("Cannot marshal type Kind");
87+ }
88+
89+ public static readonly KindConverter Singleton = new KindConverter();
90+ }
91+}
92+#pragma warning restore CS8618
93+#pragma warning restore CS8601
94+#pragma warning restore CS8602
95+#pragma warning restore CS8603
96+#pragma warning restore CS8604
97+#pragma warning restore CS8625
98+#pragma warning restore CS8765
Aschema-csharp-SystemTextJsondefault / QuickType.cs+196 −0
@@ -0,0 +1,196 @@
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("kind")]
27+ public Kind Kind { get; set; }
28+ }
29+
30+ public enum Kind { Only };
31+
32+ public partial class TopLevel
33+ {
34+ public static TopLevel FromJson(string json) => global::System.Text.Json.JsonSerializer.Deserialize<TopLevel>(json, QuickType.Converter.Settings);
35+ }
36+
37+ public static partial class Serialize
38+ {
39+ public static string ToJson(this TopLevel self) => JsonSerializer.Serialize(self, QuickType.Converter.Settings);
40+ }
41+
42+ internal static partial class Converter
43+ {
44+ public static readonly JsonSerializerOptions Settings = new(JsonSerializerDefaults.General)
45+ {
46+ Converters =
47+ {
48+ KindConverter.Singleton,
49+ new DateOnlyConverter(),
50+ new TimeOnlyConverter(),
51+ IsoDateTimeOffsetConverter.Singleton
52+ },
53+ };
54+ }
55+
56+ internal class KindConverter : JsonConverter<Kind>
57+ {
58+ public override bool CanConvert(Type t) => t == typeof(Kind);
59+
60+ public override Kind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
61+ {
62+ var value = reader.GetString();
63+ if (value == "only")
64+ {
65+ return Kind.Only;
66+ }
67+ throw new JsonException("Cannot unmarshal type Kind");
68+ }
69+
70+ public override void Write(Utf8JsonWriter writer, Kind value, JsonSerializerOptions options)
71+ {
72+ if (value == Kind.Only)
73+ {
74+ JsonSerializer.Serialize(writer, "only", options);
75+ return;
76+ }
77+ throw new NotSupportedException("Cannot marshal type Kind");
78+ }
79+
80+ public static readonly KindConverter Singleton = new KindConverter();
81+ }
82+
83+ public class DateOnlyConverter : JsonConverter<DateOnly>
84+ {
85+ private readonly string serializationFormat;
86+ public DateOnlyConverter() : this(null) { }
87+
88+ public DateOnlyConverter(string? serializationFormat)
89+ {
90+ this.serializationFormat = serializationFormat ?? "yyyy-MM-dd";
91+ }
92+
93+ public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
94+ {
95+ var value = reader.GetString();
96+ return DateOnly.Parse(value!);
97+ }
98+
99+ public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
100+ => writer.WriteStringValue(value.ToString(serializationFormat));
101+ }
102+
103+ public class TimeOnlyConverter : JsonConverter<TimeOnly>
104+ {
105+ private readonly string serializationFormat;
106+
107+ public TimeOnlyConverter() : this(null) { }
108+
109+ public TimeOnlyConverter(string? serializationFormat)
110+ {
111+ this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff";
112+ }
113+
114+ public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
115+ {
116+ var value = reader.GetString();
117+ return TimeOnly.Parse(value!);
118+ }
119+
120+ public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options)
121+ => writer.WriteStringValue(value.ToString(serializationFormat));
122+ }
123+
124+ internal class IsoDateTimeOffsetConverter : JsonConverter<DateTimeOffset>
125+ {
126+ public override bool CanConvert(Type t) => t == typeof(DateTimeOffset);
127+
128+ private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
129+
130+ private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind;
131+ private string? _dateTimeFormat;
132+ private CultureInfo? _culture;
133+
134+ public DateTimeStyles DateTimeStyles
135+ {
136+ get => _dateTimeStyles;
137+ set => _dateTimeStyles = value;
138+ }
139+
140+ public string? DateTimeFormat
141+ {
142+ get => _dateTimeFormat ?? string.Empty;
143+ set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value;
144+ }
145+
146+ public CultureInfo Culture
147+ {
148+ get => _culture ?? CultureInfo.CurrentCulture;
149+ set => _culture = value;
150+ }
151+
152+ public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
153+ {
154+ string text;
155+
156+
157+ if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
158+ || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
159+ {
160+ value = value.ToUniversalTime();
161+ }
162+
163+ text = value.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
164+
165+ writer.WriteStringValue(text);
166+ }
167+
168+ public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
169+ {
170+ string? dateText = reader.GetString();
171+
172+ if (string.IsNullOrEmpty(dateText) == false)
173+ {
174+ if (!string.IsNullOrEmpty(_dateTimeFormat))
175+ {
176+ return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
177+ }
178+ else
179+ {
180+ return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles);
181+ }
182+ }
183+ else
184+ {
185+ return default(DateTimeOffset);
186+ }
187+ }
188+
189+
190+ public static readonly IsoDateTimeOffsetConverter Singleton = new IsoDateTimeOffsetConverter();
191+ }
192+}
193+#pragma warning restore CS8618
194+#pragma warning restore CS8601
195+#pragma warning restore CS8602
196+#pragma warning restore CS8603
Aschema-csharpdefault / QuickType.cs+98 −0
@@ -0,0 +1,98 @@
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("kind", Required = Required.Always)]
29+ public Kind Kind { get; set; }
30+ }
31+
32+ public enum Kind { Only };
33+
34+ public partial class TopLevel
35+ {
36+ public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings);
37+ }
38+
39+ public static partial class Serialize
40+ {
41+ public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
42+ }
43+
44+ internal static partial class Converter
45+ {
46+ public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
47+ {
48+ MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
49+ DateParseHandling = DateParseHandling.None,
50+ Converters =
51+ {
52+ KindConverter.Singleton,
53+ new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
54+ },
55+ };
56+ }
57+
58+ internal class KindConverter : JsonConverter
59+ {
60+ public override bool CanConvert(Type t) => t == typeof(Kind) || t == typeof(Kind?);
61+
62+ public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
63+ {
64+ if (reader.TokenType == JsonToken.Null) return null;
65+ var value = serializer.Deserialize<string>(reader);
66+ if (value == "only")
67+ {
68+ return Kind.Only;
69+ }
70+ throw new Exception("Cannot unmarshal type Kind");
71+ }
72+
73+ public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
74+ {
75+ if (untypedValue == null)
76+ {
77+ serializer.Serialize(writer, null);
78+ return;
79+ }
80+ var value = (Kind)untypedValue;
81+ if (value == Kind.Only)
82+ {
83+ serializer.Serialize(writer, "only");
84+ return;
85+ }
86+ throw new Exception("Cannot marshal type Kind");
87+ }
88+
89+ public static readonly KindConverter Singleton = new KindConverter();
90+ }
91+}
92+#pragma warning restore CS8618
93+#pragma warning restore CS8601
94+#pragma warning restore CS8602
95+#pragma warning restore CS8603
96+#pragma warning restore CS8604
97+#pragma warning restore CS8625
98+#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 Kind kind;
13+
14+ TopLevel({
15+ required this.kind,
16+ });
17+
18+ factory TopLevel.fromJson(Map<String, dynamic> json) => TopLevel(
19+ kind: kindValues.map[json["kind"]]!,
20+ );
21+
22+ Map<String, dynamic> toJson() => {
23+ "kind": kindValues.reverse[kind],
24+ };
25+}
26+
27+enum Kind {
28+ ONLY
29+}
30+
31+final kindValues = EnumValues({
32+ "only": Kind.ONLY
33+});
34+
35+class EnumValues<T> {
36+ Map<String, T> map;
37+ late Map<T, String> reverseMap;
38+
39+ EnumValues(this.map);
40+
41+ Map<T, String> get reverse {
42+ reverseMap = map.map((k, v) => MapEntry(v, k));
43+ return reverseMap;
44+ }
45+}
Aschema-elixirdefault / QuickType.ex+84 −0
@@ -0,0 +1,84 @@
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 Kind do
9+ @valid_enum_members [
10+ :only,
11+ ]
12+
13+ def valid_atom?(value), do: value in @valid_enum_members
14+
15+ def valid_atom_string?(value) do
16+ try do
17+ atom = String.to_existing_atom(value)
18+ atom in @valid_enum_members
19+ rescue
20+ ArgumentError -> false
21+ end
22+ end
23+
24+ def encode(value) do
25+ if valid_atom?(value) do
26+ Atom.to_string(value)
27+ else
28+ {:error, "Unexpected value when encoding atom: #{inspect(value)}"}
29+ end
30+ end
31+
32+ def decode(value) do
33+ if valid_atom_string?(value) do
34+ String.to_existing_atom(value)
35+ else
36+ {:error, "Unexpected value when decoding atom: #{inspect(value)}"}
37+ end
38+ end
39+
40+ def from_json(json) do
41+ json
42+ |> Jason.decode!()
43+ |> decode()
44+ end
45+
46+ def to_json(data) do
47+ data
48+ |> encode()
49+ |> Jason.encode!()
50+ end
51+end
52+
53+defmodule TopLevel do
54+ @enforce_keys [:kind]
55+ defstruct [:kind]
56+
57+ @type t :: %__MODULE__{
58+ kind: Kind.t()
59+ }
60+
61+ def from_map(m) do
62+ %TopLevel{
63+ kind: Kind.decode(m["kind"]),
64+ }
65+ end
66+
67+ def from_json(json) do
68+ json
69+ |> Jason.decode!()
70+ |> from_map()
71+ end
72+
73+ def to_map(struct) do
74+ %{
75+ "kind" => Kind.encode(struct.kind),
76+ }
77+ end
78+
79+ def to_json(struct) do
80+ struct
81+ |> to_map()
82+ |> Jason.encode!()
83+ end
84+end
Aschema-elmdefault / QuickType.elm+74 −0
@@ -0,0 +1,74 @@
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+ , Kind(..)
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+ { kind : Kind
28+ }
29+
30+type Kind
31+ = Only
32+
33+-- decoders and encoders
34+optionalField key decoder fallback =
35+ Jdec.dict Jdec.value
36+ |> Jdec.andThen (\m ->
37+ case Dict.get key m of
38+ Nothing -> Jdec.succeed fallback
39+ Just x -> Jdec.decodeValue decoder x |> Result.map Jdec.succeed |> Result.withDefault (Jdec.fail ("Invalid " ++ key)))
40+
41+quickTypeToString : QuickType -> String
42+quickTypeToString r = Jenc.encode 0 (encodeQuickType r)
43+
44+quickType : Jdec.Decoder QuickType
45+quickType =
46+ Jdec.succeed QuickType
47+ |> Jpipe.required "kind" kind
48+
49+encodeQuickType : QuickType -> Jenc.Value
50+encodeQuickType x =
51+ Jenc.object
52+ [ ("kind", encodeKind x.kind)
53+ ]
54+
55+kind : Jdec.Decoder Kind
56+kind =
57+ Jdec.string
58+ |> Jdec.andThen (\str ->
59+ case str of
60+ "only" -> Jdec.succeed Only
61+ somethingElse -> Jdec.fail <| "Invalid Kind: " ++ somethingElse
62+ )
63+
64+encodeKind : Kind -> Jenc.Value
65+encodeKind x = case x of
66+ Only -> Jenc.string "only"
67+
68+--- encoder helpers
69+
70+makeNullableEncoder : (a -> Jenc.Value) -> Maybe a -> Jenc.Value
71+makeNullableEncoder f m =
72+ case m of
73+ Just x -> f x
74+ Nothing -> Jenc.null
Aschema-flowdefault / TopLevel.js+216 −0
@@ -0,0 +1,216 @@
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+ kind: Kind;
14+ [property: string]: mixed;
15+};
16+
17+export type Kind =
18+ "only";
19+
20+// Converts JSON strings to/from your types
21+// and asserts the results of JSON.parse at runtime
22+function toTopLevel(json: string): TopLevel {
23+ return cast(JSON.parse(json), r("TopLevel"));
24+}
25+
26+function topLevelToJson(value: TopLevel): string {
27+ return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
28+}
29+
30+function invalidValue(typ: any, val: any, key: any, parent: any = '') {
31+ const prettyTyp = prettyTypeName(typ);
32+ const parentText = parent ? ` on ${parent}` : '';
33+ const keyText = key ? ` for key "${key}"` : '';
34+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
35+}
36+
37+function prettyTypeName(typ: any): string {
38+ if (Array.isArray(typ)) {
39+ if (typ.length === 2 && typ[0] === undefined) {
40+ return `an optional ${prettyTypeName(typ[1])}`;
41+ } else {
42+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
43+ }
44+ } else if (typeof typ === "object" && typ.literal !== undefined) {
45+ return typ.literal;
46+ } else {
47+ return typeof typ;
48+ }
49+}
50+
51+function jsonToJSProps(typ: any): any {
52+ if (typ.jsonToJS === undefined) {
53+ const map: any = {};
54+ typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
55+ typ.jsonToJS = map;
56+ }
57+ return typ.jsonToJS;
58+}
59+
60+function jsToJSONProps(typ: any): any {
61+ if (typ.jsToJSON === undefined) {
62+ const map: any = {};
63+ typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
64+ typ.jsToJSON = map;
65+ }
66+ return typ.jsToJSON;
67+}
68+
69+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
70+ function transformPrimitive(typ: string, val: any): any {
71+ if (typeof typ === typeof val) return val;
72+ return invalidValue(typ, val, key, parent);
73+ }
74+
75+ function transformUnion(typs: any[], val: any): any {
76+ // val must validate against one typ in typs
77+ const l = typs.length;
78+ for (let i = 0; i < l; i++) {
79+ const typ = typs[i];
80+ try {
81+ return transform(val, typ, getProps);
82+ } catch (_) {}
83+ }
84+ return invalidValue(typs, val, key, parent);
85+ }
86+
87+ function transformEnum(cases: string[], val: any): any {
88+ if (cases.indexOf(val) !== -1) return val;
89+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
90+ }
91+
92+ function transformArray(typ: any, val: any): any {
93+ // val must be an array with no invalid elements
94+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
95+
96+ return val.map(el => transform(el, typ, getProps));
97+ }
98+
99+ function transformDate(val: any): any {
100+ if (val === null) {
101+ return null;
102+ }
103+ const d = new Date(val);
104+ if (isNaN(d.valueOf())) {
105+ return invalidValue(l("Date"), val, key, parent);
106+ }
107+ return d;
108+ }
109+
110+ function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
111+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
112+ return invalidValue(l(ref || "object"), val, key, parent);
113+ }
114+ const result: any = {};
115+ Object.getOwnPropertyNames(props).forEach(key => {
116+ const prop = props[key];
117+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
118+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
119+ });
120+ Object.getOwnPropertyNames(val).forEach(key => {
121+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
122+ result[key] = transform(val[key], additional, getProps, key, ref);
123+ }
124+ });
125+ return result;
126+ }
127+
128+ if (typ === "any") return val;
129+ if (typ === null) {
130+ if (val === null) return val;
131+ return invalidValue(typ, val, key, parent);
132+ }
133+ if (typ === false) return invalidValue(typ, val, key, parent);
134+ let ref: any = undefined;
135+ while (typeof typ === "object" && typ.ref !== undefined) {
136+ ref = typ.ref;
137+ typ = typeMap[typ.ref];
138+ }
139+ if (Array.isArray(typ)) return transformEnum(typ, val);
140+ if (typeof typ === "object") {
141+ return typ.hasOwnProperty("pattern") ? typeof val === "string" && new RegExp(typ.pattern).test(val) ? val : invalidValue(typ, val, key, parent)
142+ : typ.hasOwnProperty("string") ? typeof val === "string" && (typ.min === undefined || val.length >= typ.min) && (typ.max === undefined || val.length <= typ.max) ? transform(val, typ.string, getProps, key, parent) : invalidValue(typ, val, key, parent)
143+ : typ.hasOwnProperty("number") ? typeof val === "number" && (typ.min === undefined || val >= typ.min) && (typ.max === undefined || val <= typ.max) ? transform(val, typ.number, getProps, key, parent) : invalidValue(typ, val, key, parent)
144+ : typ.hasOwnProperty("integer") ? typeof val === "number" && val % 1 === 0 ? val : invalidValue(l("integer"), val, key, parent)
145+ : typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
146+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
147+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
148+ : invalidValue(typ, val, key, parent);
149+ }
150+ // Numbers can be parsed by Date but shouldn't be.
151+ if (typ === Date && typeof val !== "number") return transformDate(val);
152+ return transformPrimitive(typ, val);
153+}
154+
155+function cast<T>(val: any, typ: any): T {
156+ return transform(val, typ, jsonToJSProps);
157+}
158+
159+function uncast<T>(val: T, typ: any): any {
160+ return transform(val, typ, jsToJSONProps);
161+}
162+
163+function l(typ: any) {
164+ return { literal: typ };
165+}
166+
167+function a(typ: any) {
168+ return { arrayItems: typ };
169+}
170+
171+function i(typ: any) {
172+ return { integer: typ };
173+}
174+
175+function p(pattern: any) {
176+ return { pattern };
177+}
178+
179+function s(typ: any, min: any, max: any) {
180+ return { string: typ, min, max };
181+}
182+
183+function n(typ: any, min: any, max: any) {
184+ return { number: typ, min, max };
185+}
186+
187+function u(...typs: any[]) {
188+ return { unionMembers: typs };
189+}
190+
191+function o(props: any[], additional: any) {
192+ return { props, additional };
193+}
194+
195+function m(additional: any) {
196+ const props: any[] = [];
197+ return { props, additional };
198+}
199+
200+function r(name: string) {
201+ return { ref: name };
202+}
203+
204+const typeMap: any = {
205+ "TopLevel": o([
206+ { json: "kind", js: "kind", typ: r("Kind") },
207+ ], "any"),
208+ "Kind": [
209+ "only",
210+ ],
211+};
212+
213+module.exports = {
214+ "topLevelToJson": topLevelToJson,
215+ "toTopLevel": toTopLevel,
216+};
Aschema-golangdefault / quicktype.go+41 −0
@@ -0,0 +1,41 @@
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+ Kind Kind `json:"kind"`
23+}
24+
25+type Kind string
26+
27+const (
28+ Only Kind = "only"
29+)
30+
31+type invalidKind string
32+func (x invalidKind) Error() string { return "invalid Kind: " + string(x) }
33+
34+func (x *Kind) UnmarshalJSON(data []byte) error {
35+ var value string
36+ if err := json.Unmarshal(data, &value); err != nil { return err }
37+ switch Kind(value) {
38+ case Only: *x = Kind(value); return nil
39+ }
40+ return invalidKind(value)
41+}
Aschema-haskelldefault / QuickType.hs+43 −0
@@ -0,0 +1,43 @@
1+{-# LANGUAGE StrictData #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+
4+module QuickType
5+ ( QuickType (..)
6+ , Kind (..)
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+ { kindQuickType :: Kind
18+ } deriving (Show)
19+
20+data Kind
21+ = OnlyKind
22+ deriving (Show)
23+
24+decodeTopLevel :: ByteString -> Maybe QuickType
25+decodeTopLevel = decode
26+
27+instance ToJSON QuickType where
28+ toJSON (QuickType kindQuickType) =
29+ object
30+ [ "kind" .= kindQuickType
31+ ]
32+
33+instance FromJSON QuickType where
34+ parseJSON (Object v) = QuickType
35+ <$> v .: "kind"
36+
37+instance ToJSON Kind where
38+ toJSON OnlyKind = "only"
39+
40+instance FromJSON Kind where
41+ parseJSON = withText "Kind" parseText
42+ where
43+ parseText "only" = return OnlyKind
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / Converter.java+123 −0
@@ -0,0 +1,123 @@
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 com.fasterxml.jackson.core.type.TypeReference;
23+import java.util.*;
24+import java.util.Date;
25+import java.text.SimpleDateFormat;
26+
27+public class Converter {
28+ // Date-time helpers
29+
30+ private static final String[] DATE_TIME_FORMATS = {
31+ "yyyy-MM-dd'T'HH:mm:ss.SX",
32+ "yyyy-MM-dd'T'HH:mm:ss.S",
33+ "yyyy-MM-dd'T'HH:mm:ssX",
34+ "yyyy-MM-dd'T'HH:mm:ss",
35+ "yyyy-MM-dd HH:mm:ss.SX",
36+ "yyyy-MM-dd HH:mm:ss.S",
37+ "yyyy-MM-dd HH:mm:ssX",
38+ "yyyy-MM-dd HH:mm:ss",
39+ "HH:mm:ss.SZ",
40+ "HH:mm:ss.S",
41+ "HH:mm:ssZ",
42+ "HH:mm:ss",
43+ "yyyy-MM-dd",
44+ };
45+
46+ public static Date parseAllDateTimeString(String str) {
47+ str = str.replaceFirst("(\\.\\d{3})\\d+", "$1");
48+ for (String format : DATE_TIME_FORMATS) {
49+ try {
50+ return new SimpleDateFormat(format).parse(str);
51+ } catch (Exception ex) {
52+ // Ignored
53+ }
54+ }
55+ return null;
56+ }
57+
58+ public static String serializeDateTime(Date datetime) {
59+ return new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ").format(datetime);
60+ }
61+
62+ public static String serializeDate(Date datetime) {
63+ return new SimpleDateFormat("yyyy-MM-dd").format(datetime);
64+ }
65+
66+ public static String serializeTime(Date datetime) {
67+ return new SimpleDateFormat("hh:mm:ssZ").format(datetime);
68+ }
69+ // Serialize/deserialize helpers
70+
71+ public static TopLevel fromJsonString(String json) throws IOException {
72+ return getObjectReader().readValue(json);
73+ }
74+
75+ public static String toJsonString(TopLevel obj) throws JsonProcessingException {
76+ return getObjectWriter().writeValueAsString(obj);
77+ }
78+
79+ private static ObjectReader reader;
80+ private static ObjectWriter writer;
81+
82+ private static void instantiateMapper() {
83+ ObjectMapper mapper = new ObjectMapper();
84+ mapper.findAndRegisterModules();
85+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
86+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
87+ SimpleModule module = new SimpleModule();
88+ module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
89+ @Override
90+ public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
91+ String value = jsonParser.getText();
92+ return Converter.parseAllDateTimeString(value);
93+ }
94+ });
95+ module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
96+ @Override
97+ public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
98+ String value = jsonParser.getText();
99+ return Converter.parseAllDateTimeString(value);
100+ }
101+ });
102+ module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
103+ @Override
104+ public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
105+ String value = jsonParser.getText();
106+ return Converter.parseAllDateTimeString(value);
107+ }
108+ });
109+ mapper.registerModule(module);
110+ reader = mapper.readerFor(TopLevel.class);
111+ writer = mapper.writerFor(TopLevel.class);
112+ }
113+
114+ private static ObjectReader getObjectReader() {
115+ if (reader == null) instantiateMapper();
116+ return reader;
117+ }
118+
119+ private static ObjectWriter getObjectWriter() {
120+ if (writer == null) instantiateMapper();
121+ return writer;
122+ }
123+}
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / Kind.java+22 −0
@@ -0,0 +1,22 @@
1+package io.quicktype;
2+
3+import java.io.IOException;
4+import com.fasterxml.jackson.annotation.*;
5+
6+public enum Kind {
7+ ONLY;
8+
9+ @JsonValue
10+ public String toValue() {
11+ switch (this) {
12+ case ONLY: return "only";
13+ }
14+ return null;
15+ }
16+
17+ @JsonCreator
18+ public static Kind forValue(String value) throws IOException {
19+ if (value.equals("only")) return ONLY;
20+ throw new IOException("Cannot deserialize Kind");
21+ }
22+}
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / TopLevel.java+12 −0
@@ -0,0 +1,12 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class TopLevel {
6+ private Kind kind;
7+
8+ @JsonProperty("kind")
9+ public Kind getKind() { return kind; }
10+ @JsonProperty("kind")
11+ public void setKind(Kind value) { this.kind = value; }
12+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / Converter.java+102 −0
@@ -0,0 +1,102 @@
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 com.fasterxml.jackson.core.type.TypeReference;
23+import java.util.*;
24+import java.time.LocalDate;
25+import java.time.OffsetDateTime;
26+import java.time.OffsetTime;
27+import java.time.ZoneOffset;
28+import java.time.ZonedDateTime;
29+import java.time.format.DateTimeFormatter;
30+import java.time.format.DateTimeFormatterBuilder;
31+import java.time.temporal.ChronoField;
32+
33+public class Converter {
34+ // Date-time helpers
35+
36+ private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
37+ .appendOptional(DateTimeFormatter.ISO_DATE_TIME)
38+ .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
39+ .appendOptional(DateTimeFormatter.ISO_INSTANT)
40+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX"))
41+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX"))
42+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
43+ .toFormatter()
44+ .withZone(ZoneOffset.UTC);
45+
46+ public static OffsetDateTime parseDateTimeString(String str) {
47+ return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();
48+ }
49+
50+ private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
51+ .appendOptional(DateTimeFormatter.ISO_TIME)
52+ .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)
53+ .parseDefaulting(ChronoField.YEAR, 2020)
54+ .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
55+ .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
56+ .toFormatter()
57+ .withZone(ZoneOffset.UTC);
58+
59+ public static OffsetTime parseTimeString(String str) {
60+ return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();
61+ }
62+ // Serialize/deserialize helpers
63+
64+ public static TopLevel fromJsonString(String json) throws IOException {
65+ return getObjectReader().readValue(json);
66+ }
67+
68+ public static String toJsonString(TopLevel obj) throws JsonProcessingException {
69+ return getObjectWriter().writeValueAsString(obj);
70+ }
71+
72+ private static ObjectReader reader;
73+ private static ObjectWriter writer;
74+
75+ private static void instantiateMapper() {
76+ ObjectMapper mapper = new ObjectMapper();
77+ mapper.findAndRegisterModules();
78+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
79+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
80+ SimpleModule module = new SimpleModule();
81+ module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
82+ @Override
83+ public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
84+ String value = jsonParser.getText();
85+ return Converter.parseDateTimeString(value);
86+ }
87+ });
88+ mapper.registerModule(module);
89+ reader = mapper.readerFor(TopLevel.class);
90+ writer = mapper.writerFor(TopLevel.class);
91+ }
92+
93+ private static ObjectReader getObjectReader() {
94+ if (reader == null) instantiateMapper();
95+ return reader;
96+ }
97+
98+ private static ObjectWriter getObjectWriter() {
99+ if (writer == null) instantiateMapper();
100+ return writer;
101+ }
102+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / Kind.java+22 −0
@@ -0,0 +1,22 @@
1+package io.quicktype;
2+
3+import java.io.IOException;
4+import com.fasterxml.jackson.annotation.*;
5+
6+public enum Kind {
7+ ONLY;
8+
9+ @JsonValue
10+ public String toValue() {
11+ switch (this) {
12+ case ONLY: return "only";
13+ }
14+ return null;
15+ }
16+
17+ @JsonCreator
18+ public static Kind forValue(String value) throws IOException {
19+ if (value.equals("only")) return ONLY;
20+ throw new IOException("Cannot deserialize Kind");
21+ }
22+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / TopLevel.java+12 −0
@@ -0,0 +1,12 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class TopLevel {
6+ private Kind kind;
7+
8+ @JsonProperty("kind")
9+ public Kind getKind() { return kind; }
10+ @JsonProperty("kind")
11+ public void setKind(Kind value) { this.kind = value; }
12+}
Aschema-javadefault / src / main / java / io / quicktype / Converter.java+102 −0
@@ -0,0 +1,102 @@
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 com.fasterxml.jackson.core.type.TypeReference;
23+import java.util.*;
24+import java.time.LocalDate;
25+import java.time.OffsetDateTime;
26+import java.time.OffsetTime;
27+import java.time.ZoneOffset;
28+import java.time.ZonedDateTime;
29+import java.time.format.DateTimeFormatter;
30+import java.time.format.DateTimeFormatterBuilder;
31+import java.time.temporal.ChronoField;
32+
33+public class Converter {
34+ // Date-time helpers
35+
36+ private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
37+ .appendOptional(DateTimeFormatter.ISO_DATE_TIME)
38+ .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
39+ .appendOptional(DateTimeFormatter.ISO_INSTANT)
40+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX"))
41+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX"))
42+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
43+ .toFormatter()
44+ .withZone(ZoneOffset.UTC);
45+
46+ public static OffsetDateTime parseDateTimeString(String str) {
47+ return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();
48+ }
49+
50+ private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
51+ .appendOptional(DateTimeFormatter.ISO_TIME)
52+ .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)
53+ .parseDefaulting(ChronoField.YEAR, 2020)
54+ .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
55+ .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
56+ .toFormatter()
57+ .withZone(ZoneOffset.UTC);
58+
59+ public static OffsetTime parseTimeString(String str) {
60+ return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();
61+ }
62+ // Serialize/deserialize helpers
63+
64+ public static TopLevel fromJsonString(String json) throws IOException {
65+ return getObjectReader().readValue(json);
66+ }
67+
68+ public static String toJsonString(TopLevel obj) throws JsonProcessingException {
69+ return getObjectWriter().writeValueAsString(obj);
70+ }
71+
72+ private static ObjectReader reader;
73+ private static ObjectWriter writer;
74+
75+ private static void instantiateMapper() {
76+ ObjectMapper mapper = new ObjectMapper();
77+ mapper.findAndRegisterModules();
78+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
79+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
80+ SimpleModule module = new SimpleModule();
81+ module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
82+ @Override
83+ public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
84+ String value = jsonParser.getText();
85+ return Converter.parseDateTimeString(value);
86+ }
87+ });
88+ mapper.registerModule(module);
89+ reader = mapper.readerFor(TopLevel.class);
90+ writer = mapper.writerFor(TopLevel.class);
91+ }
92+
93+ private static ObjectReader getObjectReader() {
94+ if (reader == null) instantiateMapper();
95+ return reader;
96+ }
97+
98+ private static ObjectWriter getObjectWriter() {
99+ if (writer == null) instantiateMapper();
100+ return writer;
101+ }
102+}
Aschema-javadefault / src / main / java / io / quicktype / Kind.java+22 −0
@@ -0,0 +1,22 @@
1+package io.quicktype;
2+
3+import java.io.IOException;
4+import com.fasterxml.jackson.annotation.*;
5+
6+public enum Kind {
7+ ONLY;
8+
9+ @JsonValue
10+ public String toValue() {
11+ switch (this) {
12+ case ONLY: return "only";
13+ }
14+ return null;
15+ }
16+
17+ @JsonCreator
18+ public static Kind forValue(String value) throws IOException {
19+ if (value.equals("only")) return ONLY;
20+ throw new IOException("Cannot deserialize Kind");
21+ }
22+}
Aschema-javadefault / src / main / java / io / quicktype / TopLevel.java+12 −0
@@ -0,0 +1,12 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class TopLevel {
6+ private Kind kind;
7+
8+ @JsonProperty("kind")
9+ public Kind getKind() { return kind; }
10+ @JsonProperty("kind")
11+ public void setKind(Kind value) { this.kind = value; }
12+}
Aschema-javascript-prop-typesdefault / toplevel.js+21 −0
@@ -0,0 +1,21 @@
1+// Example usage:
2+//
3+// import { MyShape } from ./myShape.js;
4+//
5+// class MyComponent extends React.Component {
6+// //
7+// }
8+//
9+// MyComponent.propTypes = {
10+// input: MyShape
11+// };
12+
13+import PropTypes from "prop-types";
14+
15+let _TopLevel;
16+const _Kind = PropTypes.oneOf(['only']);
17+_TopLevel = PropTypes.shape({
18+ "kind": _Kind,
19+});
20+
21+export const TopLevel = _TopLevel;
Aschema-javascriptdefault / TopLevel.js+206 −0
@@ -0,0 +1,206 @@
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+
86+ return val.map(el => transform(el, typ, getProps));
87+ }
88+
89+ function transformDate(val) {
90+ if (val === null) {
91+ return null;
92+ }
93+ const d = new Date(val);
94+ if (isNaN(d.valueOf())) {
95+ return invalidValue(l("Date"), val, key, parent);
96+ }
97+ return d;
98+ }
99+
100+ function transformObject(props, additional, val) {
101+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
102+ return invalidValue(l(ref || "object"), val, key, parent);
103+ }
104+ const result = {};
105+ Object.getOwnPropertyNames(props).forEach(key => {
106+ const prop = props[key];
107+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
108+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
109+ });
110+ Object.getOwnPropertyNames(val).forEach(key => {
111+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
112+ result[key] = transform(val[key], additional, getProps, key, ref);
113+ }
114+ });
115+ return result;
116+ }
117+
118+ if (typ === "any") return val;
119+ if (typ === null) {
120+ if (val === null) return val;
121+ return invalidValue(typ, val, key, parent);
122+ }
123+ if (typ === false) return invalidValue(typ, val, key, parent);
124+ let ref = undefined;
125+ while (typeof typ === "object" && typ.ref !== undefined) {
126+ ref = typ.ref;
127+ typ = typeMap[typ.ref];
128+ }
129+ if (Array.isArray(typ)) return transformEnum(typ, val);
130+ if (typeof typ === "object") {
131+ return typ.hasOwnProperty("pattern") ? typeof val === "string" && new RegExp(typ.pattern).test(val) ? val : invalidValue(typ, val, key, parent)
132+ : typ.hasOwnProperty("string") ? typeof val === "string" && (typ.min === undefined || val.length >= typ.min) && (typ.max === undefined || val.length <= typ.max) ? transform(val, typ.string, getProps, key, parent) : invalidValue(typ, val, key, parent)
133+ : typ.hasOwnProperty("number") ? typeof val === "number" && (typ.min === undefined || val >= typ.min) && (typ.max === undefined || val <= typ.max) ? transform(val, typ.number, getProps, key, parent) : invalidValue(typ, val, key, parent)
134+ : typ.hasOwnProperty("integer") ? typeof val === "number" && val % 1 === 0 ? val : invalidValue(l("integer"), val, key, parent)
135+ : typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
136+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
137+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
138+ : invalidValue(typ, val, key, parent);
139+ }
140+ // Numbers can be parsed by Date but shouldn't be.
141+ if (typ === Date && typeof val !== "number") return transformDate(val);
142+ return transformPrimitive(typ, val);
143+}
144+
145+function cast(val, typ) {
146+ return transform(val, typ, jsonToJSProps);
147+}
148+
149+function uncast(val, typ) {
150+ return transform(val, typ, jsToJSONProps);
151+}
152+
153+function l(typ) {
154+ return { literal: typ };
155+}
156+
157+function a(typ) {
158+ return { arrayItems: typ };
159+}
160+
161+function i(typ) {
162+ return { integer: typ };
163+}
164+
165+function p(pattern) {
166+ return { pattern };
167+}
168+
169+function s(typ, min, max) {
170+ return { string: typ, min, max };
171+}
172+
173+function n(typ, min, max) {
174+ return { number: typ, min, max };
175+}
176+
177+function u(...typs) {
178+ return { unionMembers: typs };
179+}
180+
181+function o(props, additional) {
182+ return { props, additional };
183+}
184+
185+function m(additional) {
186+ const props = [];
187+ return { props, additional };
188+}
189+
190+function r(name) {
191+ return { ref: name };
192+}
193+
194+const typeMap = {
195+ "TopLevel": o([
196+ { json: "kind", js: "kind", typ: r("Kind") },
197+ ], "any"),
198+ "Kind": [
199+ "only",
200+ ],
201+};
202+
203+module.exports = {
204+ "topLevelToJson": topLevelToJson,
205+ "toTopLevel": toTopLevel,
206+};
Aschema-kotlin-jacksondefault / TopLevel.kt+53 −0
@@ -0,0 +1,53 @@
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+
17+@Suppress("UNCHECKED_CAST")
18+private fun <T> ObjectMapper.convert(k: kotlin.reflect.KClass<*>, fromJson: (JsonNode) -> T, toJson: (T) -> String, isUnion: Boolean = false) = registerModule(SimpleModule().apply {
19+ addSerializer(k.java as Class<T>, object : StdSerializer<T>(k.java as Class<T>) {
20+ override fun serialize(value: T, gen: JsonGenerator, provider: SerializerProvider) = gen.writeRawValue(toJson(value))
21+ })
22+ addDeserializer(k.java as Class<T>, object : StdDeserializer<T>(k.java as Class<T>) {
23+ override fun deserialize(p: JsonParser, ctxt: DeserializationContext) = fromJson(p.readValueAsTree())
24+ })
25+})
26+
27+val mapper = jacksonObjectMapper().apply {
28+ propertyNamingStrategy = PropertyNamingStrategy.LOWER_CAMEL_CASE
29+ setSerializationInclusion(JsonInclude.Include.NON_NULL)
30+ convert(Kind::class, { Kind.fromValue(it.asText()) }, { "\"${it.value}\"" })
31+}
32+
33+data class TopLevel (
34+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
35+ val kind: Kind
36+) {
37+ fun toJson() = mapper.writeValueAsString(this)
38+
39+ companion object {
40+ fun fromJson(json: String) = mapper.readValue<TopLevel>(json)
41+ }
42+}
43+
44+enum class Kind(val value: String) {
45+ Only("only");
46+
47+ companion object {
48+ fun fromValue(value: String): Kind = when (value) {
49+ "only" -> Only
50+ else -> throw IllegalArgumentException()
51+ }
52+ }
53+}
Aschema-kotlindefault / TopLevel.kt+39 −0
@@ -0,0 +1,39 @@
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 fun <T> Klaxon.convert(k: kotlin.reflect.KClass<*>, fromJson: (JsonValue) -> T, toJson: (T) -> String, isUnion: Boolean = false) =
10+ this.converter(object: Converter {
11+ @Suppress("UNCHECKED_CAST")
12+ override fun toJson(value: Any) = toJson(value as T)
13+ override fun fromJson(jv: JsonValue) = fromJson(jv) as Any
14+ override fun canConvert(cls: Class<*>) = cls == k.java || (isUnion && cls.superclass == k.java)
15+ })
16+
17+private val klaxon = Klaxon()
18+ .convert(Kind::class, { Kind.fromValue(it.string!!) }, { "\"${it.value}\"" })
19+
20+data class TopLevel (
21+ val kind: Kind
22+) {
23+ public fun toJson() = klaxon.toJsonString(this)
24+
25+ companion object {
26+ public fun fromJson(json: String) = klaxon.parse<TopLevel>(json)
27+ }
28+}
29+
30+enum class Kind(val value: String) {
31+ Only("only");
32+
33+ companion object {
34+ public fun fromValue(value: String): Kind = when (value) {
35+ "only" -> Only
36+ else -> throw IllegalArgumentException()
37+ }
38+ }
39+}
Aschema-kotlinxdefault / TopLevel.kt+21 −0
@@ -0,0 +1,21 @@
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 kind: Kind
16+)
17+
18+@Serializable
19+enum class Kind(val value: String) {
20+ @SerialName("only") Only("only");
21+}
Aschema-objective-cdefault / QTTopLevel.h+39 −0
@@ -0,0 +1,39 @@
1+// To parse this JSON:
2+//
3+// NSError *error;
4+// QTTopLevel *topLevel = [QTTopLevel fromJSON:json encoding:NSUTF8Encoding error:&error];
5+
6+#import <Foundation/Foundation.h>
7+
8+@class QTTopLevel;
9+@class QTKind;
10+
11+NS_ASSUME_NONNULL_BEGIN
12+
13+#pragma mark - Boxed enums
14+
15+@interface QTKind : NSObject
16+@property (nonatomic, readonly, copy) NSString *value;
17++ (instancetype _Nullable)withValue:(NSString *)value;
18++ (QTKind *)only;
19+@end
20+
21+#pragma mark - Top-level marshaling functions
22+
23+QTTopLevel *_Nullable QTTopLevelFromData(NSData *data, NSError **error);
24+QTTopLevel *_Nullable QTTopLevelFromJSON(NSString *json, NSStringEncoding encoding, NSError **error);
25+NSData *_Nullable QTTopLevelToData(QTTopLevel *topLevel, NSError **error);
26+NSString *_Nullable QTTopLevelToJSON(QTTopLevel *topLevel, NSStringEncoding encoding, NSError **error);
27+
28+#pragma mark - Object interfaces
29+
30+@interface QTTopLevel : NSObject
31+@property (nonatomic, assign) QTKind *kind;
32+
33++ (_Nullable instancetype)fromJSON:(NSString *)json encoding:(NSStringEncoding)encoding error:(NSError *_Nullable *)error;
34++ (_Nullable instancetype)fromData:(NSData *)data error:(NSError *_Nullable *)error;
35+- (NSString *_Nullable)toJSON:(NSStringEncoding)encoding error:(NSError *_Nullable *)error;
36+- (NSData *_Nullable)toData:(NSError *_Nullable *)error;
37+@end
38+
39+NS_ASSUME_NONNULL_END
Aschema-objective-cdefault / QTTopLevel.m+145 −0
@@ -0,0 +1,145 @@
1+#import "QTTopLevel.h"
2+
3+#define λ(decl, expr) (^(decl) { return (expr); })
4+
5+static id NSNullify(id _Nullable x) {
6+ return (x == nil || x == NSNull.null) ? NSNull.null : x;
7+}
8+
9+NS_ASSUME_NONNULL_BEGIN
10+
11+@interface QTTopLevel (JSONConversion)
12++ (instancetype)fromJSONDictionary:(NSDictionary *)dict;
13+- (NSDictionary *)JSONDictionary;
14+@end
15+
16+@implementation QTKind
17++ (NSDictionary<NSString *, QTKind *> *)values
18+{
19+ static NSDictionary<NSString *, QTKind *> *values;
20+ return values = values ? values : @{
21+ @"only": [[QTKind alloc] initWithValue:@"only"],
22+ };
23+}
24+
25++ (QTKind *)only { return QTKind.values[@"only"]; }
26+
27++ (instancetype _Nullable)withValue:(NSString *)value
28+{
29+ return QTKind.values[value];
30+}
31+
32+- (instancetype)initWithValue:(NSString *)value
33+{
34+ if (self = [super init]) _value = value;
35+ return self;
36+}
37+
38+- (NSUInteger)hash { return _value.hash; }
39+@end
40+
41+#pragma mark - JSON serialization
42+
43+QTTopLevel *_Nullable QTTopLevelFromData(NSData *data, NSError **error)
44+{
45+ @try {
46+ id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:error];
47+ return *error ? nil : [QTTopLevel fromJSONDictionary:json];
48+ } @catch (NSException *exception) {
49+ *error = [NSError errorWithDomain:@"JSONSerialization" code:-1 userInfo:@{ @"exception": exception }];
50+ return nil;
51+ }
52+}
53+
54+QTTopLevel *_Nullable QTTopLevelFromJSON(NSString *json, NSStringEncoding encoding, NSError **error)
55+{
56+ return QTTopLevelFromData([json dataUsingEncoding:encoding], error);
57+}
58+
59+NSData *_Nullable QTTopLevelToData(QTTopLevel *topLevel, NSError **error)
60+{
61+ @try {
62+ id json = [topLevel JSONDictionary];
63+ NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingFragmentsAllowed error:error];
64+ return *error ? nil : data;
65+ } @catch (NSException *exception) {
66+ *error = [NSError errorWithDomain:@"JSONSerialization" code:-1 userInfo:@{ @"exception": exception }];
67+ return nil;
68+ }
69+}
70+
71+NSString *_Nullable QTTopLevelToJSON(QTTopLevel *topLevel, NSStringEncoding encoding, NSError **error)
72+{
73+ NSData *data = QTTopLevelToData(topLevel, error);
74+ return data ? [[NSString alloc] initWithData:data encoding:encoding] : nil;
75+}
76+
77+@implementation QTTopLevel
78++ (NSDictionary<NSString *, NSString *> *)properties
79+{
80+ static NSDictionary<NSString *, NSString *> *properties;
81+ return properties = properties ? properties : @{
82+ @"kind": @"kind",
83+ };
84+}
85+
86++ (_Nullable instancetype)fromData:(NSData *)data error:(NSError *_Nullable *)error
87+{
88+ return QTTopLevelFromData(data, error);
89+}
90+
91++ (_Nullable instancetype)fromJSON:(NSString *)json encoding:(NSStringEncoding)encoding error:(NSError *_Nullable *)error
92+{
93+ return QTTopLevelFromJSON(json, encoding, error);
94+}
95+
96++ (instancetype)fromJSONDictionary:(NSDictionary *)dict
97+{
98+ return [dict isKindOfClass:NSDictionary.class] ? [[QTTopLevel alloc] initWithJSONDictionary:dict] : nil;
99+}
100+
101+- (instancetype)initWithJSONDictionary:(NSDictionary *)dict
102+{
103+ if (self = [super init]) {
104+ if (![dict[@"kind"] isKindOfClass:NSString.class]) return nil;
105+ [self setValuesForKeysWithDictionary:dict];
106+ _kind = [QTKind withValue:(id)_kind];
107+ }
108+ return self;
109+}
110+
111+- (void)setValue:(nullable id)value forKey:(NSString *)key
112+{
113+ id resolved = QTTopLevel.properties[key];
114+ if (resolved) [super setValue:value forKey:resolved];
115+}
116+
117+- (void)setNilValueForKey:(NSString *)key
118+{
119+ id resolved = QTTopLevel.properties[key];
120+ if (resolved) [super setValue:@(0) forKey:resolved];
121+}
122+
123+- (NSDictionary *)JSONDictionary
124+{
125+ id dict = [[self dictionaryWithValuesForKeys:QTTopLevel.properties.allValues] mutableCopy];
126+
127+ [dict addEntriesFromDictionary:@{
128+ @"kind": [_kind value],
129+ }];
130+
131+ return dict;
132+}
133+
134+- (NSData *_Nullable)toData:(NSError *_Nullable *)error
135+{
136+ return QTTopLevelToData(self, error);
137+}
138+
139+- (NSString *_Nullable)toJSON:(NSStringEncoding)encoding error:(NSError *_Nullable *)error
140+{
141+ return QTTopLevelToJSON(self, encoding, error);
142+}
143+@end
144+
145+NS_ASSUME_NONNULL_END
Aschema-phpdefault / TopLevel.php+146 −0
@@ -0,0 +1,146 @@
1+<?php
2+declare(strict_types=1);
3+
4+// This is an autogenerated file:TopLevel
5+
6+class TopLevel {
7+ private Kind $kind; // json:kind Required
8+
9+ /**
10+ * @param Kind $kind
11+ */
12+ public function __construct(Kind $kind) {
13+ $this->kind = $kind;
14+ }
15+
16+ /**
17+ * @param string $value
18+ * @throws Exception
19+ * @return Kind
20+ */
21+ public static function fromKind(string $value): Kind {
22+ return Kind::from($value); /*enum*/
23+ }
24+
25+ /**
26+ * @throws Exception
27+ * @return string
28+ */
29+ public function toKind(): string {
30+ if (TopLevel::validateKind($this->kind)) {
31+ return Kind::to($this->kind); /*enum*/
32+ }
33+ throw new Exception('never get to this TopLevel::kind');
34+ }
35+
36+ /**
37+ * @param Kind
38+ * @return bool
39+ * @throws Exception
40+ */
41+ public static function validateKind(Kind $value): bool {
42+ Kind::to($value);
43+ return true;
44+ }
45+
46+ /**
47+ * @throws Exception
48+ * @return Kind
49+ */
50+ public function getKind(): Kind {
51+ if (TopLevel::validateKind($this->kind)) {
52+ return $this->kind;
53+ }
54+ throw new Exception('never get to getKind TopLevel::kind');
55+ }
56+
57+ /**
58+ * @return Kind
59+ */
60+ public static function sampleKind(): Kind {
61+ return Kind::sample(); /*enum*/
62+ }
63+
64+ /**
65+ * @throws Exception
66+ * @return bool
67+ */
68+ public function validate(): bool {
69+ return TopLevel::validateKind($this->kind);
70+ }
71+
72+ /**
73+ * @return stdClass
74+ * @throws Exception
75+ */
76+ public function to(): stdClass {
77+ $out = new stdClass();
78+ $out->{'kind'} = $this->toKind();
79+ return $out;
80+ }
81+
82+ /**
83+ * @param stdClass $obj
84+ * @return TopLevel
85+ * @throws Exception
86+ */
87+ public static function from(stdClass $obj): TopLevel {
88+ return new TopLevel(
89+ TopLevel::fromKind($obj->{'kind'})
90+ );
91+ }
92+
93+ /**
94+ * @return TopLevel
95+ */
96+ public static function sample(): TopLevel {
97+ return new TopLevel(
98+ TopLevel::sampleKind()
99+ );
100+ }
101+}
102+
103+// This is an autogenerated file:Kind
104+
105+class Kind {
106+ public static Kind $ONLY;
107+ public static function init() {
108+ Kind::$ONLY = new Kind('only');
109+ }
110+ private string $enum;
111+ public function __construct(string $enum) {
112+ $this->enum = $enum;
113+ }
114+
115+ /**
116+ * @param Kind
117+ * @return string
118+ * @throws Exception
119+ */
120+ public static function to(Kind $obj): string {
121+ switch ($obj->enum) {
122+ case Kind::$ONLY->enum: return 'only';
123+ }
124+ throw new Exception('the give value is not an enum-value.');
125+ }
126+
127+ /**
128+ * @param mixed
129+ * @return Kind
130+ * @throws Exception
131+ */
132+ public static function from($obj): Kind {
133+ switch ($obj) {
134+ case 'only': return Kind::$ONLY;
135+ }
136+ throw new Exception("Cannot deserialize Kind");
137+ }
138+
139+ /**
140+ * @return Kind
141+ */
142+ public static function sample(): Kind {
143+ return Kind::$ONLY;
144+ }
145+}
146+Kind::init();
Aschema-pikedefault / TopLevel.pmod+41 −0
@@ -0,0 +1,41 @@
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+ Kind kind; // json: "kind"
17+
18+ string encode_json() {
19+ mapping(string:mixed) json = ([
20+ "kind" : kind,
21+ ]);
22+
23+ return Standards.JSON.encode(json);
24+ }
25+}
26+
27+TopLevel TopLevel_from_JSON(mixed json) {
28+ TopLevel retval = TopLevel();
29+
30+ retval.kind = Kind_from_JSON(json["kind"]);
31+
32+ return retval;
33+}
34+
35+enum Kind {
36+ ONLY = "only", // json: "only"
37+}
38+
39+Kind Kind_from_JSON(mixed json) {
40+ if(json&&json != "only")error("enum");return json;
41+}
Aschema-pythondefault / quicktype.py+45 −0
@@ -0,0 +1,45 @@
1+from enum import Enum
2+from dataclasses import dataclass
3+from typing import Any, TypeVar, Type, cast
4+
5+
6+T = TypeVar("T")
7+EnumT = TypeVar("EnumT", bound=Enum)
8+
9+
10+def to_enum(c: Type[EnumT], x: Any) -> EnumT:
11+ assert isinstance(x, c)
12+ return x.value
13+
14+
15+def to_class(c: Type[T], x: Any) -> dict:
16+ assert isinstance(x, c)
17+ return cast(Any, x).to_dict()
18+
19+
20+class Kind(Enum):
21+ ONLY = "only"
22+
23+
24+@dataclass
25+class TopLevel:
26+ kind: Kind
27+
28+ @staticmethod
29+ def from_dict(obj: Any) -> 'TopLevel':
30+ assert isinstance(obj, dict)
31+ kind = Kind(obj.get("kind"))
32+ return TopLevel(kind)
33+
34+ def to_dict(self) -> dict:
35+ result: dict = {}
36+ result["kind"] = to_enum(Kind, self.kind)
37+ return result
38+
39+
40+def top_level_from_dict(s: Any) -> TopLevel:
41+ return TopLevel.from_dict(s)
42+
43+
44+def top_level_to_dict(x: TopLevel) -> Any:
45+ return to_class(TopLevel, x)
Aschema-rubydefault / TopLevel.rb+50 −0
@@ -0,0 +1,50 @@
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.kind == Kind::Only
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+ Kind = Strict::String.enum("only")
21+end
22+
23+module Kind
24+ Only = "only"
25+end
26+
27+class TopLevel < Dry::Struct
28+ attribute :kind, Types::Kind
29+
30+ def self.from_dynamic!(d)
31+ d = Types::Hash[d]
32+ new(
33+ kind: d.fetch("kind"),
34+ )
35+ end
36+
37+ def self.from_json!(json)
38+ from_dynamic!(JSON.parse(json))
39+ end
40+
41+ def to_dynamic
42+ {
43+ "kind" => kind,
44+ }
45+ end
46+
47+ def to_json(options = nil)
48+ JSON.generate(to_dynamic, options)
49+ end
50+end
Aschema-rustdefault / module_under_test.rs+25 −0
@@ -0,0 +1,25 @@
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 kind: Kind,
19+}
20+
21+#[derive(Debug, Clone, Serialize, Deserialize)]
22+#[serde(rename_all = "snake_case")]
23+pub enum Kind {
24+ Only,
25+}
Aschema-scala3-upickledefault / TopLevel.scala+83 −0
@@ -0,0 +1,83 @@
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 kind : Kind
70+) derives OptionPickler.ReadWriter
71+
72+enum Kind :
73+ case Only
74+
75+given OptionPickler.ReadWriter[Kind] = OptionPickler.readwriter[String].bimap[Kind](
76+ {
77+ case Kind.Only => "only"
78+ },
79+ {
80+ case "only" => Kind.Only
81+ case other => throw new upickle.core.Abort("invalid Kind: " + other)
82+ }
83+)
Aschema-scala3default / TopLevel.scala+23 −0
@@ -0,0 +1,23 @@
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 kind : Kind
12+) derives Encoder.AsObject, Decoder
13+
14+enum Kind :
15+ case Only
16+
17+given Decoder[Kind] = Decoder.decodeString.emap {
18+ case "only" => scala.Right(Kind.Only)
19+ case other => scala.Left("invalid Kind: " + other)
20+}
21+given Encoder[Kind] = Encoder.encodeString.contramap {
22+ case Kind.Only => "only"
23+}
Aschema-schemadefault / TopLevel.schema+26 −0
@@ -0,0 +1,26 @@
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+ "kind": {
10+ "$ref": "#/definitions/Kind"
11+ }
12+ },
13+ "required": [
14+ "kind"
15+ ],
16+ "title": "TopLevel"
17+ },
18+ "Kind": {
19+ "type": "string",
20+ "enum": [
21+ "only"
22+ ],
23+ "title": "Kind"
24+ }
25+ }
26+}
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 kind: Kind
11+
12+ enum CodingKeys: String, CodingKey {
13+ case kind = "kind"
14+ }
15+}
16+
17+// MARK: TopLevel convenience initializers and mutators
18+
19+extension TopLevel {
20+ init(data: Data) throws {
21+ self = try newJSONDecoder().decode(TopLevel.self, from: data)
22+ }
23+
24+ init(_ json: String, using encoding: String.Encoding = .utf8) throws {
25+ guard let data = json.data(using: encoding) else {
26+ throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
27+ }
28+ try self.init(data: data)
29+ }
30+
31+ init(fromURL url: URL) throws {
32+ try self.init(data: try Data(contentsOf: url))
33+ }
34+
35+ func with(
36+ kind: Kind? = nil
37+ ) -> TopLevel {
38+ return TopLevel(
39+ kind: kind ?? self.kind
40+ )
41+ }
42+
43+ func jsonData() throws -> Data {
44+ return try newJSONEncoder().encode(self)
45+ }
46+
47+ func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
48+ return String(data: try self.jsonData(), encoding: encoding)
49+ }
50+}
51+
52+enum Kind: String, Codable {
53+ case only = "only"
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-effect-schemadefault / TopLevel.ts+11 −0
@@ -0,0 +1,11 @@
1+import * as S from "effect/Schema";
2+
3+
4+export const Kind = S.Literal(
5+ "only",
6+);
7+export type Kind = S.Schema.Type<typeof Kind>;
8+
9+export class TopLevel extends S.Class<TopLevel>("TopLevel")({
10+ "kind": Kind,
11+}) {}
Aschema-typescript-zoddefault / TopLevel.ts+12 −0
@@ -0,0 +1,12 @@
1+import * as z from "zod";
2+
3+
4+export const KindSchema = z.enum([
5+ "only",
6+]);
7+export type Kind = z.infer<typeof KindSchema>;
8+
9+export const TopLevelSchema = z.object({
10+ "kind": KindSchema,
11+});
12+export type TopLevel = z.infer<typeof TopLevelSchema>;
Aschema-typescript-zodprefer-const-values-true--6b26e4d1265c / TopLevel.ts+10 −0
@@ -0,0 +1,10 @@
1+import * as z from "zod";
2+
3+
4+export const KindSchema = z.literal("only");
5+export type Kind = z.infer<typeof KindSchema>;
6+
7+export const TopLevelSchema = z.object({
8+ "kind": KindSchema,
9+});
10+export type TopLevel = z.infer<typeof TopLevelSchema>;
Aschema-typescriptdefault / TopLevel.ts+210 −0
@@ -0,0 +1,210 @@
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+ kind: Kind;
12+ [property: string]: unknown;
13+}
14+
15+export type Kind = "only";
16+
17+// Converts JSON strings to/from your types
18+// and asserts the results of JSON.parse at runtime
19+export class Convert {
20+ public static toTopLevel(json: string): TopLevel {
21+ return cast(JSON.parse(json), r("TopLevel"));
22+ }
23+
24+ public static topLevelToJson(value: TopLevel): string {
25+ return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
26+ }
27+}
28+
29+function invalidValue(typ: any, val: any, key: any, parent: any = ''): never {
30+ const prettyTyp = prettyTypeName(typ);
31+ const parentText = parent ? ` on ${parent}` : '';
32+ const keyText = key ? ` for key "${key}"` : '';
33+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
34+}
35+
36+function prettyTypeName(typ: any): string {
37+ if (Array.isArray(typ)) {
38+ if (typ.length === 2 && typ[0] === undefined) {
39+ return `an optional ${prettyTypeName(typ[1])}`;
40+ } else {
41+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
42+ }
43+ } else if (typeof typ === "object" && typ.literal !== undefined) {
44+ return typ.literal;
45+ } else {
46+ return typeof typ;
47+ }
48+}
49+
50+function jsonToJSProps(typ: any): any {
51+ if (typ.jsonToJS === undefined) {
52+ const map: any = {};
53+ typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
54+ typ.jsonToJS = map;
55+ }
56+ return typ.jsonToJS;
57+}
58+
59+function jsToJSONProps(typ: any): any {
60+ if (typ.jsToJSON === undefined) {
61+ const map: any = {};
62+ typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
63+ typ.jsToJSON = map;
64+ }
65+ return typ.jsToJSON;
66+}
67+
68+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
69+ function transformPrimitive(typ: string, val: any): any {
70+ if (typeof typ === typeof val) return val;
71+ return invalidValue(typ, val, key, parent);
72+ }
73+
74+ function transformUnion(typs: any[], val: any): any {
75+ // val must validate against one typ in typs
76+ const l = typs.length;
77+ for (let i = 0; i < l; i++) {
78+ const typ = typs[i];
79+ try {
80+ return transform(val, typ, getProps);
81+ } catch (_) {}
82+ }
83+ return invalidValue(typs, val, key, parent);
84+ }
85+
86+ function transformEnum(cases: string[], val: any): any {
87+ if (cases.indexOf(val) !== -1) return val;
88+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
89+ }
90+
91+ function transformArray(typ: any, val: any): any {
92+ // val must be an array with no invalid elements
93+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
94+
95+ return val.map(el => transform(el, typ, getProps));
96+ }
97+
98+ function transformDate(val: any): any {
99+ if (val === null) {
100+ return null;
101+ }
102+ const d = new Date(val);
103+ if (isNaN(d.valueOf())) {
104+ return invalidValue(l("Date"), val, key, parent);
105+ }
106+ return d;
107+ }
108+
109+ function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
110+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
111+ return invalidValue(l(ref || "object"), val, key, parent);
112+ }
113+ const result: any = {};
114+ Object.getOwnPropertyNames(props).forEach(key => {
115+ const prop = props[key];
116+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
117+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
118+ });
119+ Object.getOwnPropertyNames(val).forEach(key => {
120+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
121+ result[key] = transform(val[key], additional, getProps, key, ref);
122+ }
123+ });
124+ return result;
125+ }
126+
127+ if (typ === "any") return val;
128+ if (typ === null) {
129+ if (val === null) return val;
130+ return invalidValue(typ, val, key, parent);
131+ }
132+ if (typ === false) return invalidValue(typ, val, key, parent);
133+ let ref: any = undefined;
134+ while (typeof typ === "object" && typ.ref !== undefined) {
135+ ref = typ.ref;
136+ typ = typeMap[typ.ref];
137+ }
138+ if (Array.isArray(typ)) return transformEnum(typ, val);
139+ if (typeof typ === "object") {
140+ return typ.hasOwnProperty("pattern") ? typeof val === "string" && new RegExp(typ.pattern).test(val) ? val : invalidValue(typ, val, key, parent)
141+ : typ.hasOwnProperty("string") ? typeof val === "string" && (typ.min === undefined || val.length >= typ.min) && (typ.max === undefined || val.length <= typ.max) ? transform(val, typ.string, getProps, key, parent) : invalidValue(typ, val, key, parent)
142+ : typ.hasOwnProperty("number") ? typeof val === "number" && (typ.min === undefined || val >= typ.min) && (typ.max === undefined || val <= typ.max) ? transform(val, typ.number, getProps, key, parent) : invalidValue(typ, val, key, parent)
143+ : typ.hasOwnProperty("integer") ? typeof val === "number" && val % 1 === 0 ? val : invalidValue(l("integer"), val, key, parent)
144+ : typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
145+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
146+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
147+ : invalidValue(typ, val, key, parent);
148+ }
149+ // Numbers can be parsed by Date but shouldn't be.
150+ if (typ === Date && typeof val !== "number") return transformDate(val);
151+ return transformPrimitive(typ, val);
152+}
153+
154+function cast<T>(val: any, typ: any): T {
155+ return transform(val, typ, jsonToJSProps);
156+}
157+
158+function uncast<T>(val: T, typ: any): any {
159+ return transform(val, typ, jsToJSONProps);
160+}
161+
162+function l(typ: any) {
163+ return { literal: typ };
164+}
165+
166+function a(typ: any) {
167+ return { arrayItems: typ };
168+}
169+
170+function i(typ: any) {
171+ return { integer: typ };
172+}
173+
174+function p(pattern: any) {
175+ return { pattern };
176+}
177+
178+function s(typ: any, min: any, max: any) {
179+ return { string: typ, min, max };
180+}
181+
182+function n(typ: any, min: any, max: any) {
183+ return { number: typ, min, max };
184+}
185+
186+function u(...typs: any[]) {
187+ return { unionMembers: typs };
188+}
189+
190+function o(props: any[], additional: any) {
191+ return { props, additional };
192+}
193+
194+function m(additional: any) {
195+ const props: any[] = [];
196+ return { props, additional };
197+}
198+
199+function r(name: string) {
200+ return { ref: name };
201+}
202+
203+const typeMap: any = {
204+ "TopLevel": o([
205+ { json: "kind", js: "kind", typ: r("Kind") },
206+ ], "any"),
207+ "Kind": [
208+ "only",
209+ ],
210+};
No generated files match these filters.