Generated-output differences

quicktype output changed between the PR base and tested PR merge revisions.
← Back to the pull request
57files differ
3modified
54new
0deleted
3,675changed lines
+3,660 −15insertions / deletions
Base 3df8d2010453809da42f3a516d959c56eb8ebe37 · PR merge 2950fa97b09c1e72ea05fde58696c7991bcc654d · Head 54bf41b8850bd1e0132805190a88afd4e502d0ed · raw patch
Aschema-cjson/test/inputs/schema/top-level-array.schema/default/TopLevel.c+148 −0
@@ -0,0 +1,148 @@
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 TextClassificationOutputElement * cJSON_ParseTextClassificationOutputElement(const char * s) {
9+ struct TextClassificationOutputElement * x = NULL;
10+ if (NULL != s) {
11+ cJSON * j = cJSON_Parse(s);
12+ if (NULL != j) {
13+ x = cJSON_GetTextClassificationOutputElementValue(j);
14+ cJSON_Delete(j);
15+ }
16+ }
17+ return x;
18+}
19+
20+struct TextClassificationOutputElement * cJSON_GetTextClassificationOutputElementValue(const cJSON * j) {
21+ struct TextClassificationOutputElement * x = NULL;
22+ if (NULL != j) {
23+ if (NULL != (x = cJSON_malloc(sizeof(struct TextClassificationOutputElement)))) {
24+ memset(x, 0, sizeof(struct TextClassificationOutputElement));
25+ if (cJSON_HasObjectItem(j, "label")) {
26+ x->label = strdup(cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(j, "label")));
27+ }
28+ else {
29+ if (NULL != (x->label = cJSON_malloc(sizeof(char)))) {
30+ x->label[0] = '\0';
31+ }
32+ }
33+ if (cJSON_HasObjectItem(j, "score")) {
34+ x->score = cJSON_GetNumberValue(cJSON_GetObjectItemCaseSensitive(j, "score"));
35+ }
36+ }
37+ }
38+ return x;
39+}
40+
41+cJSON * cJSON_CreateTextClassificationOutputElement(const struct TextClassificationOutputElement * x) {
42+ cJSON * j = NULL;
43+ if (NULL != x) {
44+ if (NULL != (j = cJSON_CreateObject())) {
45+ if (NULL != x->label) {
46+ cJSON_AddStringToObject(j, "label", x->label);
47+ }
48+ else {
49+ cJSON_AddStringToObject(j, "label", "");
50+ }
51+ cJSON_AddNumberToObject(j, "score", x->score);
52+ }
53+ }
54+ return j;
55+}
56+
57+char * cJSON_PrintTextClassificationOutputElement(const struct TextClassificationOutputElement * x) {
58+ char * s = NULL;
59+ if (NULL != x) {
60+ cJSON * j = cJSON_CreateTextClassificationOutputElement(x);
61+ if (NULL != j) {
62+ s = cJSON_Print(j);
63+ cJSON_Delete(j);
64+ }
65+ }
66+ return s;
67+}
68+
69+void cJSON_DeleteTextClassificationOutputElement(struct TextClassificationOutputElement * x) {
70+ if (NULL != x) {
71+ if (NULL != x->label) {
72+ cJSON_free(x->label);
73+ }
74+ cJSON_free(x);
75+ }
76+}
77+
78+struct TopLevel * cJSON_ParseTopLevel(const char * s) {
79+ struct TopLevel * x = NULL;
80+ if (NULL != s) {
81+ cJSON * j = cJSON_Parse(s);
82+ if (NULL != j) {
83+ x = cJSON_GetTopLevelValue(j);
84+ cJSON_Delete(j);
85+ }
86+ }
87+ return x;
88+}
89+
90+struct TopLevel * cJSON_GetTopLevelValue(const cJSON * j) {
91+ struct TopLevel * x = NULL;
92+ if (NULL != j) {
93+ if (NULL != (x = cJSON_malloc(sizeof(struct TopLevel)))) {
94+ memset(x, 0, sizeof(struct TopLevel));
95+ x->value = list_create(false, NULL);
96+ if (NULL != x->value) {
97+ cJSON * e = NULL;
98+ cJSON_ArrayForEach(e, j) {
99+ list_add_tail(x->value, cJSON_GetTextClassificationOutputElementValue(e), sizeof(struct TextClassificationOutputElement *));
100+ }
101+ }
102+ }
103+ }
104+ return x;
105+}
106+
107+cJSON * cJSON_CreateTopLevel(const struct TopLevel * x) {
108+ cJSON * j = NULL;
109+ if (NULL != x) {
110+ if (NULL != x->value) {
111+ j = cJSON_CreateArray();
112+ if (NULL != j) {
113+ struct TextClassificationOutputElement * x1 = list_get_head(x->value);
114+ while (NULL != x1) {
115+ cJSON_AddItemToArray(j, cJSON_CreateTextClassificationOutputElement(x1));
116+ x1 = list_get_next(x->value);
117+ }
118+ }
119+ }
120+ }
121+ return j;
122+}
123+
124+char * cJSON_PrintTopLevel(const struct TopLevel * x) {
125+ char * s = NULL;
126+ if (NULL != x) {
127+ cJSON * j = cJSON_CreateTopLevel(x);
128+ if (NULL != j) {
129+ s = cJSON_Print(j);
130+ cJSON_Delete(j);
131+ }
132+ }
133+ return s;
134+}
135+
136+void cJSON_DeleteTopLevel(struct TopLevel * x) {
137+ if (NULL != x) {
138+ if (NULL != x->value) {
139+ struct TextClassificationOutputElement * x1 = list_get_head(x->value);
140+ while (NULL != x1) {
141+ cJSON_DeleteTextClassificationOutputElement(x1);
142+ x1 = list_get_next(x->value);
143+ }
144+ list_release(x->value);
145+ }
146+ cJSON_free(x);
147+ }
148+}
Aschema-cjson/test/inputs/schema/top-level-array.schema/default/TopLevel.h+62 −0
@@ -0,0 +1,62 @@
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 TextClassificationOutputElement {
38+ char * label;
39+ double score;
40+};
41+
42+struct TopLevel {
43+ list_t * value;
44+};
45+
46+struct TextClassificationOutputElement * cJSON_ParseTextClassificationOutputElement(const char * s);
47+struct TextClassificationOutputElement * cJSON_GetTextClassificationOutputElementValue(const cJSON * j);
48+cJSON * cJSON_CreateTextClassificationOutputElement(const struct TextClassificationOutputElement * x);
49+char * cJSON_PrintTextClassificationOutputElement(const struct TextClassificationOutputElement * x);
50+void cJSON_DeleteTextClassificationOutputElement(struct TextClassificationOutputElement * x);
51+
52+struct TopLevel * cJSON_ParseTopLevel(const char * s);
53+struct TopLevel * cJSON_GetTopLevelValue(const cJSON * j);
54+cJSON * cJSON_CreateTopLevel(const struct TopLevel * x);
55+char * cJSON_PrintTopLevel(const struct TopLevel * x);
56+void cJSON_DeleteTopLevel(struct TopLevel * x);
57+
58+#ifdef __cplusplus
59+}
60+#endif
61+
62+#endif /* __TOPLEVEL_H__ */
Aschema-cjson/test/inputs/schema/top-level-primitive-array.schema/default/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+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+ x->value = list_create(false, NULL);
26+ if (NULL != x->value) {
27+ cJSON * e = NULL;
28+ cJSON_ArrayForEach(e, j) {
29+ list_add_tail(x->value, strdup(cJSON_GetStringValue(e)), sizeof(char *));
30+ }
31+ }
32+ }
33+ }
34+ return x;
35+}
36+
37+cJSON * cJSON_CreateTopLevel(const struct TopLevel * x) {
38+ cJSON * j = NULL;
39+ if (NULL != x) {
40+ if (NULL != x->value) {
41+ j = cJSON_CreateArray();
42+ if (NULL != j) {
43+ char * x1 = list_get_head(x->value);
44+ while (NULL != x1) {
45+ cJSON_AddItemToArray(j, cJSON_CreateString(x1));
46+ x1 = list_get_next(x->value);
47+ }
48+ }
49+ }
50+ }
51+ return j;
52+}
53+
54+char * cJSON_PrintTopLevel(const struct TopLevel * x) {
55+ char * s = NULL;
56+ if (NULL != x) {
57+ cJSON * j = cJSON_CreateTopLevel(x);
58+ if (NULL != j) {
59+ s = cJSON_Print(j);
60+ cJSON_Delete(j);
61+ }
62+ }
63+ return s;
64+}
65+
66+void cJSON_DeleteTopLevel(struct TopLevel * x) {
67+ if (NULL != x) {
68+ if (NULL != x->value) {
69+ char * x1 = list_get_head(x->value);
70+ while (NULL != x1) {
71+ cJSON_free(x1);
72+ x1 = list_get_next(x->value);
73+ }
74+ list_release(x->value);
75+ }
76+ cJSON_free(x);
77+ }
78+}
Aschema-cjson/test/inputs/schema/top-level-primitive-array.schema/default/TopLevel.h+51 −0
@@ -0,0 +1,51 @@
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+ list_t * value;
39+};
40+
41+struct TopLevel * cJSON_ParseTopLevel(const char * s);
42+struct TopLevel * cJSON_GetTopLevelValue(const cJSON * j);
43+cJSON * cJSON_CreateTopLevel(const struct TopLevel * x);
44+char * cJSON_PrintTopLevel(const struct TopLevel * x);
45+void cJSON_DeleteTopLevel(struct TopLevel * x);
46+
47+#ifdef __cplusplus
48+}
49+#endif
50+
51+#endif /* __TOPLEVEL_H__ */
Aschema-cplusplus/test/inputs/schema/top-level-array.schema/default/quicktype.hpp+70 −0
@@ -0,0 +1,70 @@
1+// To parse this JSON data, first install
2+//
3+// json.hpp https://github.com/nlohmann/json
4+//
5+// Then include this file, and then do
6+//
7+// TopLevel data = nlohmann::json::parse(jsonString);
8+
9+#pragma once
10+
11+#include "json.hpp"
12+
13+#include <optional>
14+#include <stdexcept>
15+#include <regex>
16+
17+namespace quicktype {
18+ using nlohmann::json;
19+
20+ #ifndef NLOHMANN_UNTYPED_quicktype_HELPER
21+ #define NLOHMANN_UNTYPED_quicktype_HELPER
22+ inline json get_untyped(const json & j, const char * property) {
23+ if (j.find(property) != j.end()) {
24+ return j.at(property).get<json>();
25+ }
26+ return json();
27+ }
28+
29+ inline json get_untyped(const json & j, std::string property) {
30+ return get_untyped(j, property.data());
31+ }
32+ #endif
33+
34+ class TextClassificationOutputElement {
35+ public:
36+ TextClassificationOutputElement() = default;
37+ virtual ~TextClassificationOutputElement() = default;
38+
39+ private:
40+ std::string label;
41+ double score;
42+
43+ public:
44+ const std::string & get_label() const { return label; }
45+ std::string & get_mutable_label() { return label; }
46+ void set_label(const std::string & value) { this->label = value; }
47+
48+ const double & get_score() const { return score; }
49+ double & get_mutable_score() { return score; }
50+ void set_score(const double & value) { this->score = value; }
51+ };
52+
53+ using TopLevel = std::vector<TextClassificationOutputElement>;
54+}
55+
56+namespace quicktype {
57+ void from_json(const json & j, TextClassificationOutputElement & x);
58+ void to_json(json & j, const TextClassificationOutputElement & x);
59+
60+ inline void from_json(const json & j, TextClassificationOutputElement& x) {
61+ x.set_label(j.at("label").get<std::string>());
62+ x.set_score(j.at("score").get<double>());
63+ }
64+
65+ inline void to_json(json & j, const TextClassificationOutputElement & x) {
66+ j = json::object();
67+ j["label"] = x.get_label();
68+ j["score"] = x.get_score();
69+ }
70+}
Aschema-cplusplus/test/inputs/schema/top-level-primitive-array.schema/default/quicktype.hpp+35 −0
@@ -0,0 +1,35 @@
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+ using TopLevel = std::vector<std::string>;
35+}
Aschema-csharp-SystemTextJson/test/inputs/schema/top-level-array.schema/default/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("label", Required = Required.Always)]
29+ public string Label { get; set; }
30+
31+ [JsonProperty("score", Required = Required.Always)]
32+ public double Score { 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-csharp-SystemTextJson/test/inputs/schema/top-level-primitive-array.schema/default/QuickType.cs+55 −0
@@ -0,0 +1,55 @@
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 class TopLevel
27+ {
28+ public static string[] FromJson(string json) => JsonConvert.DeserializeObject<string[]>(json, QuickType.Converter.Settings);
29+ }
30+
31+ public static partial class Serialize
32+ {
33+ public static string ToJson(this string[] self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
34+ }
35+
36+ internal static partial class Converter
37+ {
38+ public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
39+ {
40+ MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
41+ DateParseHandling = DateParseHandling.None,
42+ Converters =
43+ {
44+ new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
45+ },
46+ };
47+ }
48+}
49+#pragma warning restore CS8618
50+#pragma warning restore CS8601
51+#pragma warning restore CS8602
52+#pragma warning restore CS8603
53+#pragma warning restore CS8604
54+#pragma warning restore CS8625
55+#pragma warning restore CS8765
Aschema-csharp/test/inputs/schema/top-level-array.schema/default/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+ [JsonRequired]
26+ [JsonPropertyName("label")]
27+ public string Label { get; set; }
28+
29+ [JsonRequired]
30+ [JsonPropertyName("score")]
31+ public double Score { 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-csharp/test/inputs/schema/top-level-primitive-array.schema/default/QuickType.cs+159 −0
@@ -0,0 +1,159 @@
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 class TopLevel
24+ {
25+ public static string[] FromJson(string json) => JsonSerializer.Deserialize<string[]>(json, QuickType.Converter.Settings);
26+ }
27+
28+ public static partial class Serialize
29+ {
30+ public static string ToJson(this string[] self) => JsonSerializer.Serialize(self, QuickType.Converter.Settings);
31+ }
32+
33+ internal static partial class Converter
34+ {
35+ public static readonly JsonSerializerOptions Settings = new(JsonSerializerDefaults.General)
36+ {
37+ Converters =
38+ {
39+ new DateOnlyConverter(),
40+ new TimeOnlyConverter(),
41+ IsoDateTimeOffsetConverter.Singleton
42+ },
43+ };
44+ }
45+
46+ public class DateOnlyConverter : JsonConverter<DateOnly>
47+ {
48+ private readonly string serializationFormat;
49+ public DateOnlyConverter() : this(null) { }
50+
51+ public DateOnlyConverter(string? serializationFormat)
52+ {
53+ this.serializationFormat = serializationFormat ?? "yyyy-MM-dd";
54+ }
55+
56+ public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
57+ {
58+ var value = reader.GetString();
59+ return DateOnly.Parse(value!);
60+ }
61+
62+ public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
63+ => writer.WriteStringValue(value.ToString(serializationFormat));
64+ }
65+
66+ public class TimeOnlyConverter : JsonConverter<TimeOnly>
67+ {
68+ private readonly string serializationFormat;
69+
70+ public TimeOnlyConverter() : this(null) { }
71+
72+ public TimeOnlyConverter(string? serializationFormat)
73+ {
74+ this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff";
75+ }
76+
77+ public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
78+ {
79+ var value = reader.GetString();
80+ return TimeOnly.Parse(value!);
81+ }
82+
83+ public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options)
84+ => writer.WriteStringValue(value.ToString(serializationFormat));
85+ }
86+
87+ internal class IsoDateTimeOffsetConverter : JsonConverter<DateTimeOffset>
88+ {
89+ public override bool CanConvert(Type t) => t == typeof(DateTimeOffset);
90+
91+ private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
92+
93+ private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind;
94+ private string? _dateTimeFormat;
95+ private CultureInfo? _culture;
96+
97+ public DateTimeStyles DateTimeStyles
98+ {
99+ get => _dateTimeStyles;
100+ set => _dateTimeStyles = value;
101+ }
102+
103+ public string? DateTimeFormat
104+ {
105+ get => _dateTimeFormat ?? string.Empty;
106+ set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value;
107+ }
108+
109+ public CultureInfo Culture
110+ {
111+ get => _culture ?? CultureInfo.CurrentCulture;
112+ set => _culture = value;
113+ }
114+
115+ public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
116+ {
117+ string text;
118+
119+
120+ if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
121+ || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
122+ {
123+ value = value.ToUniversalTime();
124+ }
125+
126+ text = value.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
127+
128+ writer.WriteStringValue(text);
129+ }
130+
131+ public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
132+ {
133+ string? dateText = reader.GetString();
134+
135+ if (string.IsNullOrEmpty(dateText) == false)
136+ {
137+ if (!string.IsNullOrEmpty(_dateTimeFormat))
138+ {
139+ return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
140+ }
141+ else
142+ {
143+ return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles);
144+ }
145+ }
146+ else
147+ {
148+ return default(DateTimeOffset);
149+ }
150+ }
151+
152+
153+ public static readonly IsoDateTimeOffsetConverter Singleton = new IsoDateTimeOffsetConverter();
154+ }
155+}
156+#pragma warning restore CS8618
157+#pragma warning restore CS8601
158+#pragma warning restore CS8602
159+#pragma warning restore CS8603
Aschema-dart/test/inputs/schema/top-level-array.schema/default/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+List<TopLevel> topLevelFromJson(String str) => List<TopLevel>.from(json.decode(str).map((x) => TopLevel.fromJson(x)));
8+
9+String topLevelToJson(List<TopLevel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
10+
11+class TopLevel {
12+ final String label;
13+ final double score;
14+
15+ TopLevel({
16+ required this.label,
17+ required this.score,
18+ });
19+
20+ factory TopLevel.fromJson(Map<String, dynamic> json) => TopLevel(
21+ label: json["label"],
22+ score: json["score"]?.toDouble(),
23+ );
24+
25+ Map<String, dynamic> toJson() => {
26+ "label": label,
27+ "score": score,
28+ };
29+}
Aschema-dart/test/inputs/schema/top-level-primitive-array.schema/default/TopLevel.dart+9 −0
@@ -0,0 +1,9 @@
1+// To parse this JSON data, do
2+//
3+// final topLevel = topLevelFromJson(jsonString);
4+
5+import 'dart:convert';
6+
7+List<String> topLevelFromJson(String str) => List<String>.from(json.decode(str).map((x) => x));
8+
9+String topLevelToJson(List<String> data) => json.encode(List<dynamic>.from(data.map((x) => x)));
Aschema-elm/test/inputs/schema/top-level-array.schema/default/QuickType.elm+60 −0
@@ -0,0 +1,60 @@
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+ , TextClassificationOutputElement
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 = List TextClassificationOutputElement
27+
28+type alias TextClassificationOutputElement =
29+ { label : String
30+ , score : Float
31+ }
32+
33+-- decoders and encoders
34+
35+quickType : Jdec.Decoder QuickType
36+quickType = Jdec.list textClassificationOutputElement
37+
38+quickTypeToString : QuickType -> String
39+quickTypeToString r = Jenc.encode 0 (Jenc.list encodeTextClassificationOutputElement r)
40+
41+textClassificationOutputElement : Jdec.Decoder TextClassificationOutputElement
42+textClassificationOutputElement =
43+ Jdec.succeed TextClassificationOutputElement
44+ |> Jpipe.required "label" Jdec.string
45+ |> Jpipe.required "score" Jdec.float
46+
47+encodeTextClassificationOutputElement : TextClassificationOutputElement -> Jenc.Value
48+encodeTextClassificationOutputElement x =
49+ Jenc.object
50+ [ ("label", Jenc.string x.label)
51+ , ("score", Jenc.float x.score)
52+ ]
53+
54+--- encoder helpers
55+
56+makeNullableEncoder : (a -> Jenc.Value) -> Maybe a -> Jenc.Value
57+makeNullableEncoder f m =
58+ case m of
59+ Just x -> f x
60+ Nothing -> Jenc.null
Aschema-elm/test/inputs/schema/top-level-primitive-array.schema/default/QuickType.elm+41 −0
@@ -0,0 +1,41 @@
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 = List String
26+
27+-- decoders and encoders
28+
29+quickType : Jdec.Decoder QuickType
30+quickType = Jdec.list Jdec.string
31+
32+quickTypeToString : QuickType -> String
33+quickTypeToString r = Jenc.encode 0 (Jenc.list Jenc.string r)
34+
35+--- encoder helpers
36+
37+makeNullableEncoder : (a -> Jenc.Value) -> Maybe a -> Jenc.Value
38+makeNullableEncoder f m =
39+ case m of
40+ Just x -> f x
41+ Nothing -> Jenc.null
Aschema-flow/test/inputs/schema/top-level-array.schema/default/TopLevel.js+193 −0
@@ -0,0 +1,193 @@
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 = TextClassificationOutputElement[];
13+
14+export type TextClassificationOutputElement = {
15+ label: string;
16+ score: number;
17+ [property: string]: mixed;
18+};
19+
20+// Converts JSON strings to/from your types
21+// and asserts the results of JSON.parse at runtime
22+function toTopLevel(json: string): TextClassificationOutputElement[] {
23+ return cast(JSON.parse(json), a(r("TextClassificationOutputElement")));
24+}
25+
26+function topLevelToJson(value: TextClassificationOutputElement[]): string {
27+ return JSON.stringify(uncast(value, a(r("TextClassificationOutputElement"))), 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+ 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("unionMembers") ? transformUnion(typ.unionMembers, val)
141+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
142+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
143+ : invalidValue(typ, val, key, parent);
144+ }
145+ // Numbers can be parsed by Date but shouldn't be.
146+ if (typ === Date && typeof val !== "number") return transformDate(val);
147+ return transformPrimitive(typ, val);
148+}
149+
150+function cast<T>(val: any, typ: any): T {
151+ return transform(val, typ, jsonToJSProps);
152+}
153+
154+function uncast<T>(val: T, typ: any): any {
155+ return transform(val, typ, jsToJSONProps);
156+}
157+
158+function l(typ: any) {
159+ return { literal: typ };
160+}
161+
162+function a(typ: any) {
163+ return { arrayItems: typ };
164+}
165+
166+function u(...typs: any[]) {
167+ return { unionMembers: typs };
168+}
169+
170+function o(props: any[], additional: any) {
171+ return { props, additional };
172+}
173+
174+function m(additional: any) {
175+ const props: any[] = [];
176+ return { props, additional };
177+}
178+
179+function r(name: string) {
180+ return { ref: name };
181+}
182+
183+const typeMap: any = {
184+ "TextClassificationOutputElement": o([
185+ { json: "label", js: "label", typ: "" },
186+ { json: "score", js: "score", typ: 3.14 },
187+ ], "any"),
188+};
189+
190+module.exports = {
191+ "topLevelToJson": topLevelToJson,
192+ "toTopLevel": toTopLevel,
193+};
Aschema-flow/test/inputs/schema/top-level-primitive-array.schema/default/TopLevel.js+183 −0
@@ -0,0 +1,183 @@
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 = string[];
13+
14+// Converts JSON strings to/from your types
15+// and asserts the results of JSON.parse at runtime
16+function toTopLevel(json: string): string[] {
17+ return cast(JSON.parse(json), a(""));
18+}
19+
20+function topLevelToJson(value: string[]): string {
21+ return JSON.stringify(uncast(value, a("")), null, 2);
22+}
23+
24+function invalidValue(typ: any, val: any, key: any, parent: any = '') {
25+ const prettyTyp = prettyTypeName(typ);
26+ const parentText = parent ? ` on ${parent}` : '';
27+ const keyText = key ? ` for key "${key}"` : '';
28+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
29+}
30+
31+function prettyTypeName(typ: any): string {
32+ if (Array.isArray(typ)) {
33+ if (typ.length === 2 && typ[0] === undefined) {
34+ return `an optional ${prettyTypeName(typ[1])}`;
35+ } else {
36+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
37+ }
38+ } else if (typeof typ === "object" && typ.literal !== undefined) {
39+ return typ.literal;
40+ } else {
41+ return typeof typ;
42+ }
43+}
44+
45+function jsonToJSProps(typ: any): any {
46+ if (typ.jsonToJS === undefined) {
47+ const map: any = {};
48+ typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
49+ typ.jsonToJS = map;
50+ }
51+ return typ.jsonToJS;
52+}
53+
54+function jsToJSONProps(typ: any): any {
55+ if (typ.jsToJSON === undefined) {
56+ const map: any = {};
57+ typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
58+ typ.jsToJSON = map;
59+ }
60+ return typ.jsToJSON;
61+}
62+
63+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
64+ function transformPrimitive(typ: string, val: any): any {
65+ if (typeof typ === typeof val) return val;
66+ return invalidValue(typ, val, key, parent);
67+ }
68+
69+ function transformUnion(typs: any[], val: any): any {
70+ // val must validate against one typ in typs
71+ const l = typs.length;
72+ for (let i = 0; i < l; i++) {
73+ const typ = typs[i];
74+ try {
75+ return transform(val, typ, getProps);
76+ } catch (_) {}
77+ }
78+ return invalidValue(typs, val, key, parent);
79+ }
80+
81+ function transformEnum(cases: string[], val: any): any {
82+ if (cases.indexOf(val) !== -1) return val;
83+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
84+ }
85+
86+ function transformArray(typ: any, val: any): any {
87+ // val must be an array with no invalid elements
88+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
89+ return val.map(el => transform(el, typ, getProps));
90+ }
91+
92+ function transformDate(val: any): any {
93+ if (val === null) {
94+ return null;
95+ }
96+ const d = new Date(val);
97+ if (isNaN(d.valueOf())) {
98+ return invalidValue(l("Date"), val, key, parent);
99+ }
100+ return d;
101+ }
102+
103+ function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
104+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
105+ return invalidValue(l(ref || "object"), val, key, parent);
106+ }
107+ const result: any = {};
108+ Object.getOwnPropertyNames(props).forEach(key => {
109+ const prop = props[key];
110+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
111+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
112+ });
113+ Object.getOwnPropertyNames(val).forEach(key => {
114+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
115+ result[key] = transform(val[key], additional, getProps, key, ref);
116+ }
117+ });
118+ return result;
119+ }
120+
121+ if (typ === "any") return val;
122+ if (typ === null) {
123+ if (val === null) return val;
124+ return invalidValue(typ, val, key, parent);
125+ }
126+ if (typ === false) return invalidValue(typ, val, key, parent);
127+ let ref: any = undefined;
128+ while (typeof typ === "object" && typ.ref !== undefined) {
129+ ref = typ.ref;
130+ typ = typeMap[typ.ref];
131+ }
132+ if (Array.isArray(typ)) return transformEnum(typ, val);
133+ if (typeof typ === "object") {
134+ return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
135+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
136+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
137+ : invalidValue(typ, val, key, parent);
138+ }
139+ // Numbers can be parsed by Date but shouldn't be.
140+ if (typ === Date && typeof val !== "number") return transformDate(val);
141+ return transformPrimitive(typ, val);
142+}
143+
144+function cast<T>(val: any, typ: any): T {
145+ return transform(val, typ, jsonToJSProps);
146+}
147+
148+function uncast<T>(val: T, typ: any): any {
149+ return transform(val, typ, jsToJSONProps);
150+}
151+
152+function l(typ: any) {
153+ return { literal: typ };
154+}
155+
156+function a(typ: any) {
157+ return { arrayItems: typ };
158+}
159+
160+function u(...typs: any[]) {
161+ return { unionMembers: typs };
162+}
163+
164+function o(props: any[], additional: any) {
165+ return { props, additional };
166+}
167+
168+function m(additional: any) {
169+ const props: any[] = [];
170+ return { props, additional };
171+}
172+
173+function r(name: string) {
174+ return { ref: name };
175+}
176+
177+const typeMap: any = {
178+};
179+
180+module.exports = {
181+ "topLevelToJson": topLevelToJson,
182+ "toTopLevel": toTopLevel,
183+};
Mschema-flow/test/inputs/schema/union.schema/default/TopLevel.js+8 −6
@@ -9,7 +9,9 @@
99 // These functions will throw an error if the JSON doesn't
1010 // match the expected interface, even if the JSON is valid.
1111
12-export type TopLevel = {
12+export type TopLevel = TopLevelElement[];
13+
14+export type TopLevelElement = {
1315 one?: number;
1416 two: boolean;
1517 three?: number;
@@ -18,12 +20,12 @@ export type TopLevel = {
1820
1921 // Converts JSON strings to/from your types
2022 // and asserts the results of JSON.parse at runtime
21-function toTopLevel(json: string): TopLevel[] {
22- return cast(JSON.parse(json), a(r("TopLevel")));
23+function toTopLevel(json: string): TopLevelElement[] {
24+ return cast(JSON.parse(json), a(r("TopLevelElement")));
2325 }
2426
25-function topLevelToJson(value: TopLevel[]): string {
26- return JSON.stringify(uncast(value, a(r("TopLevel"))), null, 2);
27+function topLevelToJson(value: TopLevelElement[]): string {
28+ return JSON.stringify(uncast(value, a(r("TopLevelElement"))), null, 2);
2729 }
2830
2931 function invalidValue(typ: any, val: any, key: any, parent: any = '') {
@@ -180,7 +182,7 @@ function r(name: string) {
180182 }
181183
182184 const typeMap: any = {
183- "TopLevel": o([
185+ "TopLevelElement": o([
184186 { json: "one", js: "one", typ: u(undefined, 0) },
185187 { json: "two", js: "two", typ: true },
186188 { json: "three", js: "three", typ: u(undefined, 3.14) },
Aschema-golang/test/inputs/schema/top-level-array.schema/default/quicktype.go+26 −0
@@ -0,0 +1,26 @@
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+type TopLevel []TextClassificationOutputElement
12+
13+func UnmarshalTopLevel(data []byte) (TopLevel, error) {
14+ var r TopLevel
15+ err := json.Unmarshal(data, &r)
16+ return r, err
17+}
18+
19+func (r *TopLevel) Marshal() ([]byte, error) {
20+ return json.Marshal(r)
21+}
22+
23+type TextClassificationOutputElement struct {
24+ Label string `json:"label"`
25+ Score float64 `json:"score"`
26+}
Aschema-golang/test/inputs/schema/top-level-primitive-array.schema/default/quicktype.go+21 −0
@@ -0,0 +1,21 @@
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+type TopLevel []string
12+
13+func UnmarshalTopLevel(data []byte) (TopLevel, error) {
14+ var r TopLevel
15+ err := json.Unmarshal(data, &r)
16+ return r, err
17+}
18+
19+func (r *TopLevel) Marshal() ([]byte, error) {
20+ return json.Marshal(r)
21+}
Aschema-haskell/test/inputs/schema/top-level-array.schema/default/QuickType.hs+36 −0
@@ -0,0 +1,36 @@
1+{-# LANGUAGE StrictData #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+
4+module QuickType
5+ ( QuickType (..)
6+ , TextClassificationOutputElement (..)
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+type QuickType = [TextClassificationOutputElement]
17+
18+data TextClassificationOutputElement = TextClassificationOutputElement
19+ { labelTextClassificationOutputElement :: Text
20+ , scoreTextClassificationOutputElement :: Float
21+ } deriving (Show)
22+
23+decodeTopLevel :: ByteString -> Maybe QuickType
24+decodeTopLevel = decode
25+
26+instance ToJSON TextClassificationOutputElement where
27+ toJSON (TextClassificationOutputElement labelTextClassificationOutputElement scoreTextClassificationOutputElement) =
28+ object
29+ [ "label" .= labelTextClassificationOutputElement
30+ , "score" .= scoreTextClassificationOutputElement
31+ ]
32+
33+instance FromJSON TextClassificationOutputElement where
34+ parseJSON (Object v) = TextClassificationOutputElement
35+ <$> v .: "label"
36+ <*> v .: "score"
Aschema-haskell/test/inputs/schema/top-level-primitive-array.schema/default/QuickType.hs+18 −0
@@ -0,0 +1,18 @@
1+{-# LANGUAGE StrictData #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+
4+module QuickType
5+ ( QuickType (..)
6+ , decodeTopLevel
7+ ) where
8+
9+import Data.Aeson
10+import Data.Aeson.Types (emptyObject)
11+import Data.ByteString.Lazy (ByteString)
12+import Data.HashMap.Strict (HashMap)
13+import Data.Text (Text)
14+
15+type QuickType = [Text]
16+
17+decodeTopLevel :: ByteString -> Maybe QuickType
18+decodeTopLevel = decode
Aschema-java-datetime-legacy/test/inputs/schema/top-level-array.schema/default/src/main/java/io/quicktype/Converter.java+101 −0
@@ -0,0 +1,101 @@
1+// To use this code, add the following Maven dependency to your project:
2+//
3+//
4+// com.fasterxml.jackson.core : jackson-databind : 2.9.0
5+// com.fasterxml.jackson.datatype : jackson-datatype-jsr310 : 2.9.0
6+//
7+// Import this package:
8+//
9+// import io.quicktype.Converter;
10+//
11+// Then you can deserialize a JSON string with
12+//
13+// List<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 List<TopLevel> fromJsonString(String json) throws IOException {
64+ return getObjectReader().readValue(json);
65+ }
66+
67+ public static String toJsonString(List<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(List.class);
89+ writer = mapper.writerFor(List.class);
90+ }
91+
92+ private static ObjectReader getObjectReader() {
93+ if (reader == null) instantiateMapper();
94+ return reader;
95+ }
96+
97+ private static ObjectWriter getObjectWriter() {
98+ if (writer == null) instantiateMapper();
99+ return writer;
100+ }
101+}
Aschema-java-datetime-legacy/test/inputs/schema/top-level-array.schema/default/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 label;
7+ private double score;
8+
9+ @JsonProperty("label")
10+ public String getLabel() { return label; }
11+ @JsonProperty("label")
12+ public void setLabel(String value) { this.label = value; }
13+
14+ @JsonProperty("score")
15+ public double getScore() { return score; }
16+ @JsonProperty("score")
17+ public void setScore(double value) { this.score = value; }
18+}
Aschema-java-datetime-legacy/test/inputs/schema/top-level-primitive-array.schema/default/src/main/java/io/quicktype/Converter.java+101 −0
@@ -0,0 +1,101 @@
1+// To use this code, add the following Maven dependency to your project:
2+//
3+//
4+// com.fasterxml.jackson.core : jackson-databind : 2.9.0
5+// com.fasterxml.jackson.datatype : jackson-datatype-jsr310 : 2.9.0
6+//
7+// Import this package:
8+//
9+// import io.quicktype.Converter;
10+//
11+// Then you can deserialize a JSON string with
12+//
13+// List<String> 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 List<String> fromJsonString(String json) throws IOException {
64+ return getObjectReader().readValue(json);
65+ }
66+
67+ public static String toJsonString(List<String> 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(List.class);
89+ writer = mapper.writerFor(List.class);
90+ }
91+
92+ private static ObjectReader getObjectReader() {
93+ if (reader == null) instantiateMapper();
94+ return reader;
95+ }
96+
97+ private static ObjectWriter getObjectWriter() {
98+ if (writer == null) instantiateMapper();
99+ return writer;
100+ }
101+}
Aschema-java-datetime-legacy/test/inputs/schema/top-level-primitive-array.schema/default/src/main/java/io/quicktype/TopLevel.java+4 −0
@@ -0,0 +1,4 @@
1+package io.quicktype;
2+
3+public class TopLevel {
4+}
Aschema-java-lombok/test/inputs/schema/top-level-array.schema/default/src/main/java/io/quicktype/Converter.java+121 −0
@@ -0,0 +1,121 @@
1+// To use this code, add the following Maven dependency to your project:
2+//
3+//
4+// com.fasterxml.jackson.core : jackson-databind : 2.9.0
5+//
6+//
7+// Import this package:
8+//
9+// import io.quicktype.Converter;
10+//
11+// Then you can deserialize a JSON string with
12+//
13+// List<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 List<TopLevel> fromJsonString(String json) throws IOException {
70+ return getObjectReader().readValue(json);
71+ }
72+
73+ public static String toJsonString(List<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(List.class);
109+ writer = mapper.writerFor(List.class);
110+ }
111+
112+ private static ObjectReader getObjectReader() {
113+ if (reader == null) instantiateMapper();
114+ return reader;
115+ }
116+
117+ private static ObjectWriter getObjectWriter() {
118+ if (writer == null) instantiateMapper();
119+ return writer;
120+ }
121+}
Aschema-java-lombok/test/inputs/schema/top-level-array.schema/default/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 label;
7+ private double score;
8+
9+ @JsonProperty("label")
10+ public String getLabel() { return label; }
11+ @JsonProperty("label")
12+ public void setLabel(String value) { this.label = value; }
13+
14+ @JsonProperty("score")
15+ public double getScore() { return score; }
16+ @JsonProperty("score")
17+ public void setScore(double value) { this.score = value; }
18+}
Aschema-java-lombok/test/inputs/schema/top-level-primitive-array.schema/default/src/main/java/io/quicktype/Converter.java+121 −0
@@ -0,0 +1,121 @@
1+// To use this code, add the following Maven dependency to your project:
2+//
3+//
4+// com.fasterxml.jackson.core : jackson-databind : 2.9.0
5+//
6+//
7+// Import this package:
8+//
9+// import io.quicktype.Converter;
10+//
11+// Then you can deserialize a JSON string with
12+//
13+// List<String> 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 List<String> fromJsonString(String json) throws IOException {
70+ return getObjectReader().readValue(json);
71+ }
72+
73+ public static String toJsonString(List<String> 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(List.class);
109+ writer = mapper.writerFor(List.class);
110+ }
111+
112+ private static ObjectReader getObjectReader() {
113+ if (reader == null) instantiateMapper();
114+ return reader;
115+ }
116+
117+ private static ObjectWriter getObjectWriter() {
118+ if (writer == null) instantiateMapper();
119+ return writer;
120+ }
121+}
Aschema-java-lombok/test/inputs/schema/top-level-primitive-array.schema/default/src/main/java/io/quicktype/TopLevel.java+4 −0
@@ -0,0 +1,4 @@
1+package io.quicktype;
2+
3+public class TopLevel {
4+}
Aschema-java/test/inputs/schema/top-level-array.schema/default/src/main/java/io/quicktype/Converter.java+101 −0
@@ -0,0 +1,101 @@
1+// To use this code, add the following Maven dependency to your project:
2+//
3+//
4+// com.fasterxml.jackson.core : jackson-databind : 2.9.0
5+// com.fasterxml.jackson.datatype : jackson-datatype-jsr310 : 2.9.0
6+//
7+// Import this package:
8+//
9+// import io.quicktype.Converter;
10+//
11+// Then you can deserialize a JSON string with
12+//
13+// List<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 List<TopLevel> fromJsonString(String json) throws IOException {
64+ return getObjectReader().readValue(json);
65+ }
66+
67+ public static String toJsonString(List<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(List.class);
89+ writer = mapper.writerFor(List.class);
90+ }
91+
92+ private static ObjectReader getObjectReader() {
93+ if (reader == null) instantiateMapper();
94+ return reader;
95+ }
96+
97+ private static ObjectWriter getObjectWriter() {
98+ if (writer == null) instantiateMapper();
99+ return writer;
100+ }
101+}
Aschema-java/test/inputs/schema/top-level-array.schema/default/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 label;
7+ private double score;
8+
9+ @JsonProperty("label")
10+ public String getLabel() { return label; }
11+ @JsonProperty("label")
12+ public void setLabel(String value) { this.label = value; }
13+
14+ @JsonProperty("score")
15+ public double getScore() { return score; }
16+ @JsonProperty("score")
17+ public void setScore(double value) { this.score = value; }
18+}
Aschema-java/test/inputs/schema/top-level-primitive-array.schema/default/src/main/java/io/quicktype/Converter.java+101 −0
@@ -0,0 +1,101 @@
1+// To use this code, add the following Maven dependency to your project:
2+//
3+//
4+// com.fasterxml.jackson.core : jackson-databind : 2.9.0
5+// com.fasterxml.jackson.datatype : jackson-datatype-jsr310 : 2.9.0
6+//
7+// Import this package:
8+//
9+// import io.quicktype.Converter;
10+//
11+// Then you can deserialize a JSON string with
12+//
13+// List<String> 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 List<String> fromJsonString(String json) throws IOException {
64+ return getObjectReader().readValue(json);
65+ }
66+
67+ public static String toJsonString(List<String> 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(List.class);
89+ writer = mapper.writerFor(List.class);
90+ }
91+
92+ private static ObjectReader getObjectReader() {
93+ if (reader == null) instantiateMapper();
94+ return reader;
95+ }
96+
97+ private static ObjectWriter getObjectWriter() {
98+ if (writer == null) instantiateMapper();
99+ return writer;
100+ }
101+}
Aschema-java/test/inputs/schema/top-level-primitive-array.schema/default/src/main/java/io/quicktype/TopLevel.java+4 −0
@@ -0,0 +1,4 @@
1+package io.quicktype;
2+
3+public class TopLevel {
4+}
Aschema-javascript/test/inputs/schema/top-level-array.schema/default/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), a(r("TextClassificationOutputElement")));
14+}
15+
16+function topLevelToJson(value) {
17+ return JSON.stringify(uncast(value, a(r("TextClassificationOutputElement"))), 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+ "TextClassificationOutputElement": o([
175+ { json: "label", js: "label", typ: "" },
176+ { json: "score", js: "score", typ: 3.14 },
177+ ], "any"),
178+};
179+
180+module.exports = {
181+ "topLevelToJson": topLevelToJson,
182+ "toTopLevel": toTopLevel,
183+};
Aschema-javascript/test/inputs/schema/top-level-primitive-array.schema/default/TopLevel.js+179 −0
@@ -0,0 +1,179 @@
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), a(""));
14+}
15+
16+function topLevelToJson(value) {
17+ return JSON.stringify(uncast(value, a("")), 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+};
175+
176+module.exports = {
177+ "topLevelToJson": topLevelToJson,
178+ "toTopLevel": toTopLevel,
179+};
Mschema-javascript/test/inputs/schema/union.schema/default/TopLevel.js+3 −3
@@ -10,11 +10,11 @@
1010 // Converts JSON strings to/from your types
1111 // and asserts the results of JSON.parse at runtime
1212 function toTopLevel(json) {
13- return cast(JSON.parse(json), a(r("TopLevel")));
13+ return cast(JSON.parse(json), a(r("TopLevelElement")));
1414 }
1515
1616 function topLevelToJson(value) {
17- return JSON.stringify(uncast(value, a(r("TopLevel"))), null, 2);
17+ return JSON.stringify(uncast(value, a(r("TopLevelElement"))), null, 2);
1818 }
1919
2020 function invalidValue(typ, val, key, parent = '') {
@@ -171,7 +171,7 @@ function r(name) {
171171 }
172172
173173 const typeMap = {
174- "TopLevel": o([
174+ "TopLevelElement": o([
175175 { json: "one", js: "one", typ: u(undefined, 0) },
176176 { json: "two", js: "two", typ: true },
177177 { json: "three", js: "three", typ: u(undefined, 3.14) },
Aschema-kotlin/test/inputs/schema/top-level-array.schema/default/TopLevel.kt+22 −0
@@ -0,0 +1,22 @@
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+class TopLevel(elements: Collection<TextClassificationOutputElement>) : ArrayList<TextClassificationOutputElement>(elements) {
12+ public fun toJson() = klaxon.toJsonString(this)
13+
14+ companion object {
15+ public fun fromJson(json: String) = TopLevel(klaxon.parseArray<TextClassificationOutputElement>(json)!!)
16+ }
17+}
18+
19+data class TextClassificationOutputElement (
20+ val label: String,
21+ val score: Double
22+)
Aschema-kotlin/test/inputs/schema/top-level-primitive-array.schema/default/TopLevel.kt+17 −0
@@ -0,0 +1,17 @@
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+class TopLevel(elements: Collection<String>) : ArrayList<String>(elements) {
12+ public fun toJson() = klaxon.toJsonString(this)
13+
14+ companion object {
15+ public fun fromJson(json: String) = TopLevel(klaxon.parseArray<String>(json)!!)
16+ }
17+}
Aschema-pike/test/inputs/schema/top-level-array.schema/default/TopLevel.pmod+42 −0
@@ -0,0 +1,42 @@
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+typedef array(TextClassificationOutputElement) TopLevel;
16+
17+TopLevel TopLevel_from_JSON(mixed json) {
18+ return map(json, TextClassificationOutputElement_from_JSON);
19+}
20+
21+class TextClassificationOutputElement {
22+ string label; // json: "label"
23+ float score; // json: "score"
24+
25+ string encode_json() {
26+ mapping(string:mixed) json = ([
27+ "label" : label,
28+ "score" : score,
29+ ]);
30+
31+ return Standards.JSON.encode(json);
32+ }
33+}
34+
35+TextClassificationOutputElement TextClassificationOutputElement_from_JSON(mixed json) {
36+ TextClassificationOutputElement retval = TextClassificationOutputElement();
37+
38+ retval.label = json["label"];
39+ retval.score = json["score"];
40+
41+ return retval;
42+}
Aschema-pike/test/inputs/schema/top-level-primitive-array.schema/default/TopLevel.pmod+19 −0
@@ -0,0 +1,19 @@
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+typedef array(string) TopLevel;
16+
17+TopLevel TopLevel_from_JSON(mixed json) {
18+ return json;
19+}
Aschema-python/test/inputs/schema/top-level-array.schema/default/quicktype.py+57 −0
@@ -0,0 +1,57 @@
1+from dataclasses import dataclass
2+from typing import Any, TypeVar, Callable, 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_float(x: Any) -> float:
14+ assert isinstance(x, (float, int)) and not isinstance(x, bool)
15+ return float(x)
16+
17+
18+def to_float(x: Any) -> float:
19+ assert isinstance(x, (int, float))
20+ return x
21+
22+
23+def from_list(f: Callable[[Any], T], x: Any) -> list[T]:
24+ assert isinstance(x, list)
25+ return [f(y) for y in x]
26+
27+
28+def to_class(c: Type[T], x: Any) -> dict:
29+ assert isinstance(x, c)
30+ return cast(Any, x).to_dict()
31+
32+
33+@dataclass
34+class TextClassificationOutputElement:
35+ label: str
36+ score: float
37+
38+ @staticmethod
39+ def from_dict(obj: Any) -> 'TextClassificationOutputElement':
40+ assert isinstance(obj, dict)
41+ label = from_str(obj.get("label"))
42+ score = from_float(obj.get("score"))
43+ return TextClassificationOutputElement(label, score)
44+
45+ def to_dict(self) -> dict:
46+ result: dict = {}
47+ result["label"] = from_str(self.label)
48+ result["score"] = to_float(self.score)
49+ return result
50+
51+
52+def top_level_from_dict(s: Any) -> list[TextClassificationOutputElement]:
53+ return from_list(TextClassificationOutputElement.from_dict, s)
54+
55+
56+def top_level_to_dict(x: list[TextClassificationOutputElement]) -> Any:
57+ return from_list(lambda x: to_class(TextClassificationOutputElement, x), x)
Aschema-python/test/inputs/schema/top-level-primitive-array.schema/default/quicktype.py+22 −0
@@ -0,0 +1,22 @@
1+from typing import Any, TypeVar, Callable
2+
3+
4+T = TypeVar("T")
5+
6+
7+def from_list(f: Callable[[Any], T], x: Any) -> list[T]:
8+ assert isinstance(x, list)
9+ return [f(y) for y in x]
10+
11+
12+def from_str(x: Any) -> str:
13+ assert isinstance(x, str)
14+ return x
15+
16+
17+def top_level_from_dict(s: Any) -> list[str]:
18+ return from_list(from_str, s)
19+
20+
21+def top_level_to_dict(x: list[str]) -> Any:
22+ return from_list(from_str, x)
Aschema-ruby/test/inputs/schema/top-level-array.schema/default/TopLevel.rb+59 −0
@@ -0,0 +1,59 @@
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.first.label
8+#
9+# If from_json! succeeds, the value returned matches the schema.
10+
11+require 'json'
12+require 'dry-types'
13+require 'dry-struct'
14+
15+module Types
16+ include Dry.Types(default: :nominal)
17+
18+ Hash = Strict::Hash
19+ String = Strict::String
20+ Double = Strict::Float | Strict::Integer
21+end
22+
23+class TextClassificationOutputElement < Dry::Struct
24+ attribute :label, Types::String
25+ attribute :score, Types::Double
26+
27+ def self.from_dynamic!(d)
28+ d = Types::Hash[d]
29+ new(
30+ label: d.fetch("label"),
31+ score: d.fetch("score"),
32+ )
33+ end
34+
35+ def self.from_json!(json)
36+ from_dynamic!(JSON.parse(json))
37+ end
38+
39+ def to_dynamic
40+ {
41+ "label" => label,
42+ "score" => score,
43+ }
44+ end
45+
46+ def to_json(options = nil)
47+ JSON.generate(to_dynamic, options)
48+ end
49+end
50+
51+class TopLevel
52+ def self.from_json!(json)
53+ top_level = JSON.parse(json, quirks_mode: true).map { |x| TextClassificationOutputElement.from_dynamic!(x) }
54+ top_level.define_singleton_method(:to_json) do
55+ JSON.generate(self.map { |x| x.to_dynamic })
56+ end
57+ top_level
58+ end
59+end
Aschema-ruby/test/inputs/schema/top-level-primitive-array.schema/default/TopLevel.rb+29 −0
@@ -0,0 +1,29 @@
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.first
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+ String = Strict::String
19+end
20+
21+class TopLevel
22+ def self.from_json!(json)
23+ top_level = JSON.parse(json, quirks_mode: true).map { |x| Types::String[x] }
24+ top_level.define_singleton_method(:to_json) do
25+ JSON.generate(self)
26+ end
27+ top_level
28+ end
29+end
Aschema-rust/test/inputs/schema/top-level-array.schema/default/module_under_test.rs+23 −0
@@ -0,0 +1,23 @@
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+pub type TopLevel = Vec<TextClassificationOutputElement>;
17+
18+#[derive(Debug, Clone, Serialize, Deserialize)]
19+pub struct TextClassificationOutputElement {
20+ pub label: String,
21+
22+ pub score: f64,
23+}
Aschema-rust/test/inputs/schema/top-level-primitive-array.schema/default/module_under_test.rs+16 −0
@@ -0,0 +1,16 @@
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+pub type TopLevel = Vec<String>;
Aschema-scala3-upickle/test/inputs/schema/top-level-array.schema/default/TopLevel.scala+16 −0
@@ -0,0 +1,16 @@
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+type TopLevel = List[TextClassificationOutputElement]
11+given (using ev : TextClassificationOutputElement): Encoder[Seq[TextClassificationOutputElement]] = Encoder.encodeSeq[TextClassificationOutputElement]
12+
13+case class TextClassificationOutputElement (
14+ val label : String,
15+ val score : Double
16+) derives Encoder.AsObject, Decoder
Aschema-scala3-upickle/test/inputs/schema/top-level-primitive-array.schema/default/TopLevel.scala+11 −0
@@ -0,0 +1,11 @@
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+type TopLevel = List[String]
11+given (using ev : String): Encoder[Seq[String]] = Encoder.encodeSeq[String]
Aschema-scala3/test/inputs/schema/top-level-array.schema/default/TopLevel.scala+73 −0
@@ -0,0 +1,73 @@
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+type TopLevel = List[TextClassificationOutputElement]
69+
70+case class TextClassificationOutputElement (
71+ val label : String,
72+ val score : Double
73+) derives OptionPickler.ReadWriter
Aschema-scala3/test/inputs/schema/top-level-primitive-array.schema/default/TopLevel.scala+68 −0
@@ -0,0 +1,68 @@
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+type TopLevel = List[String]
Aschema-schema/test/inputs/schema/top-level-array.schema/default/TopLevel.schema+26 −0
@@ -0,0 +1,26 @@
1+{
2+ "$schema": "http://json-schema.org/draft-06/schema#",
3+ "type": "array",
4+ "items": {
5+ "$ref": "#/definitions/TextClassificationOutputElement"
6+ },
7+ "definitions": {
8+ "TextClassificationOutputElement": {
9+ "type": "object",
10+ "additionalProperties": {},
11+ "properties": {
12+ "label": {
13+ "type": "string"
14+ },
15+ "score": {
16+ "type": "number"
17+ }
18+ },
19+ "required": [
20+ "label",
21+ "score"
22+ ],
23+ "title": "TextClassificationOutputElement"
24+ }
25+ }
26+}
Aschema-schema/test/inputs/schema/top-level-primitive-array.schema/default/TopLevel.schema+8 −0
@@ -0,0 +1,8 @@
1+{
2+ "$schema": "http://json-schema.org/draft-06/schema#",
3+ "type": "array",
4+ "items": {
5+ "type": "string"
6+ },
7+ "definitions": {}
8+}
Aschema-swift/test/inputs/schema/top-level-array.schema/default/quicktype.swift+117 −0
@@ -0,0 +1,117 @@
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: - TextClassificationOutputElement
9+struct TextClassificationOutputElement: Codable {
10+ let label: String
11+ let score: Double
12+
13+ enum CodingKeys: String, CodingKey {
14+ case label = "label"
15+ case score = "score"
16+ }
17+}
18+
19+// MARK: TextClassificationOutputElement convenience initializers and mutators
20+
21+extension TextClassificationOutputElement {
22+ init(data: Data) throws {
23+ self = try newJSONDecoder().decode(TextClassificationOutputElement.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+ label: String? = nil,
39+ score: Double? = nil
40+ ) -> TextClassificationOutputElement {
41+ return TextClassificationOutputElement(
42+ label: label ?? self.label,
43+ score: score ?? self.score
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+typealias TopLevel = [TextClassificationOutputElement]
57+
58+extension Array where Element == TopLevel.Element {
59+ init(data: Data) throws {
60+ self = try newJSONDecoder().decode(TopLevel.self, from: data)
61+ }
62+
63+ init(_ json: String, using encoding: String.Encoding = .utf8) throws {
64+ guard let data = json.data(using: encoding) else {
65+ throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
66+ }
67+ try self.init(data: data)
68+ }
69+
70+ init(fromURL url: URL) throws {
71+ try self.init(data: try Data(contentsOf: url))
72+ }
73+
74+ func jsonData() throws -> Data {
75+ return try newJSONEncoder().encode(self)
76+ }
77+
78+ func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
79+ return String(data: try self.jsonData(), encoding: encoding)
80+ }
81+}
82+
83+// MARK: - Helper functions for creating encoders and decoders
84+
85+func newJSONDecoder() -> JSONDecoder {
86+ let decoder = JSONDecoder()
87+ decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in
88+ let container = try decoder.singleValueContainer()
89+ let dateStr = try container.decode(String.self)
90+
91+ let formatter = DateFormatter()
92+ formatter.calendar = Calendar(identifier: .iso8601)
93+ formatter.locale = Locale(identifier: "en_US_POSIX")
94+ formatter.timeZone = TimeZone(secondsFromGMT: 0)
95+ formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
96+ if let date = formatter.date(from: dateStr) {
97+ return date
98+ }
99+ formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
100+ if let date = formatter.date(from: dateStr) {
101+ return date
102+ }
103+ throw DecodingError.typeMismatch(Date.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not decode date"))
104+ })
105+ return decoder
106+}
107+
108+func newJSONEncoder() -> JSONEncoder {
109+ let encoder = JSONEncoder()
110+ let formatter = DateFormatter()
111+ formatter.calendar = Calendar(identifier: .iso8601)
112+ formatter.locale = Locale(identifier: "en_US_POSIX")
113+ formatter.timeZone = TimeZone(secondsFromGMT: 0)
114+ formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
115+ encoder.dateEncodingStrategy = .formatted(formatter)
116+ return encoder
117+}
Aschema-swift/test/inputs/schema/top-level-primitive-array.schema/default/quicktype.swift+68 −0
@@ -0,0 +1,68 @@
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+import Foundation
6+
7+typealias TopLevel = [String]
8+
9+extension Array where Element == TopLevel.Element {
10+ init(data: Data) throws {
11+ self = try newJSONDecoder().decode(TopLevel.self, from: data)
12+ }
13+
14+ init(_ json: String, using encoding: String.Encoding = .utf8) throws {
15+ guard let data = json.data(using: encoding) else {
16+ throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
17+ }
18+ try self.init(data: data)
19+ }
20+
21+ init(fromURL url: URL) throws {
22+ try self.init(data: try Data(contentsOf: url))
23+ }
24+
25+ func jsonData() throws -> Data {
26+ return try newJSONEncoder().encode(self)
27+ }
28+
29+ func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
30+ return String(data: try self.jsonData(), encoding: encoding)
31+ }
32+}
33+
34+// MARK: - Helper functions for creating encoders and decoders
35+
36+func newJSONDecoder() -> JSONDecoder {
37+ let decoder = JSONDecoder()
38+ decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in
39+ let container = try decoder.singleValueContainer()
40+ let dateStr = try container.decode(String.self)
41+
42+ let formatter = DateFormatter()
43+ formatter.calendar = Calendar(identifier: .iso8601)
44+ formatter.locale = Locale(identifier: "en_US_POSIX")
45+ formatter.timeZone = TimeZone(secondsFromGMT: 0)
46+ formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
47+ if let date = formatter.date(from: dateStr) {
48+ return date
49+ }
50+ formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
51+ if let date = formatter.date(from: dateStr) {
52+ return date
53+ }
54+ throw DecodingError.typeMismatch(Date.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not decode date"))
55+ })
56+ return decoder
57+}
58+
59+func newJSONEncoder() -> JSONEncoder {
60+ let encoder = JSONEncoder()
61+ let formatter = DateFormatter()
62+ formatter.calendar = Calendar(identifier: .iso8601)
63+ formatter.locale = Locale(identifier: "en_US_POSIX")
64+ formatter.timeZone = TimeZone(secondsFromGMT: 0)
65+ formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
66+ encoder.dateEncodingStrategy = .formatted(formatter)
67+ return encoder
68+}
Aschema-typescript/test/inputs/schema/top-level-array.schema/default/TopLevel.ts+188 −0
@@ -0,0 +1,188 @@
1+// To parse this data:
2+//
3+// import { Convert } 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 type TopLevel = TextClassificationOutputElement[];
11+
12+export interface TextClassificationOutputElement {
13+ label: string;
14+ score: number;
15+ [property: string]: unknown;
16+}
17+
18+// Converts JSON strings to/from your types
19+// and asserts the results of JSON.parse at runtime
20+export class Convert {
21+ public static toTopLevel(json: string): TextClassificationOutputElement[] {
22+ return cast(JSON.parse(json), a(r("TextClassificationOutputElement")));
23+ }
24+
25+ public static topLevelToJson(value: TextClassificationOutputElement[]): string {
26+ return JSON.stringify(uncast(value, a(r("TextClassificationOutputElement"))), null, 2);
27+ }
28+}
29+
30+function invalidValue(typ: any, val: any, key: any, parent: any = ''): never {
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+ 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("unionMembers") ? transformUnion(typ.unionMembers, val)
141+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
142+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
143+ : invalidValue(typ, val, key, parent);
144+ }
145+ // Numbers can be parsed by Date but shouldn't be.
146+ if (typ === Date && typeof val !== "number") return transformDate(val);
147+ return transformPrimitive(typ, val);
148+}
149+
150+function cast<T>(val: any, typ: any): T {
151+ return transform(val, typ, jsonToJSProps);
152+}
153+
154+function uncast<T>(val: T, typ: any): any {
155+ return transform(val, typ, jsToJSONProps);
156+}
157+
158+function l(typ: any) {
159+ return { literal: typ };
160+}
161+
162+function a(typ: any) {
163+ return { arrayItems: typ };
164+}
165+
166+function u(...typs: any[]) {
167+ return { unionMembers: typs };
168+}
169+
170+function o(props: any[], additional: any) {
171+ return { props, additional };
172+}
173+
174+function m(additional: any) {
175+ const props: any[] = [];
176+ return { props, additional };
177+}
178+
179+function r(name: string) {
180+ return { ref: name };
181+}
182+
183+const typeMap: any = {
184+ "TextClassificationOutputElement": o([
185+ { json: "label", js: "label", typ: "" },
186+ { json: "score", js: "score", typ: 3.14 },
187+ ], "any"),
188+};
Aschema-typescript/test/inputs/schema/top-level-primitive-array.schema/default/TopLevel.ts+178 −0
@@ -0,0 +1,178 @@
1+// To parse this data:
2+//
3+// import { Convert } 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 type TopLevel = string[];
11+
12+// Converts JSON strings to/from your types
13+// and asserts the results of JSON.parse at runtime
14+export class Convert {
15+ public static toTopLevel(json: string): string[] {
16+ return cast(JSON.parse(json), a(""));
17+ }
18+
19+ public static topLevelToJson(value: string[]): string {
20+ return JSON.stringify(uncast(value, a("")), null, 2);
21+ }
22+}
23+
24+function invalidValue(typ: any, val: any, key: any, parent: any = ''): never {
25+ const prettyTyp = prettyTypeName(typ);
26+ const parentText = parent ? ` on ${parent}` : '';
27+ const keyText = key ? ` for key "${key}"` : '';
28+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
29+}
30+
31+function prettyTypeName(typ: any): string {
32+ if (Array.isArray(typ)) {
33+ if (typ.length === 2 && typ[0] === undefined) {
34+ return `an optional ${prettyTypeName(typ[1])}`;
35+ } else {
36+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
37+ }
38+ } else if (typeof typ === "object" && typ.literal !== undefined) {
39+ return typ.literal;
40+ } else {
41+ return typeof typ;
42+ }
43+}
44+
45+function jsonToJSProps(typ: any): any {
46+ if (typ.jsonToJS === undefined) {
47+ const map: any = {};
48+ typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
49+ typ.jsonToJS = map;
50+ }
51+ return typ.jsonToJS;
52+}
53+
54+function jsToJSONProps(typ: any): any {
55+ if (typ.jsToJSON === undefined) {
56+ const map: any = {};
57+ typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
58+ typ.jsToJSON = map;
59+ }
60+ return typ.jsToJSON;
61+}
62+
63+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
64+ function transformPrimitive(typ: string, val: any): any {
65+ if (typeof typ === typeof val) return val;
66+ return invalidValue(typ, val, key, parent);
67+ }
68+
69+ function transformUnion(typs: any[], val: any): any {
70+ // val must validate against one typ in typs
71+ const l = typs.length;
72+ for (let i = 0; i < l; i++) {
73+ const typ = typs[i];
74+ try {
75+ return transform(val, typ, getProps);
76+ } catch (_) {}
77+ }
78+ return invalidValue(typs, val, key, parent);
79+ }
80+
81+ function transformEnum(cases: string[], val: any): any {
82+ if (cases.indexOf(val) !== -1) return val;
83+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
84+ }
85+
86+ function transformArray(typ: any, val: any): any {
87+ // val must be an array with no invalid elements
88+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
89+ return val.map(el => transform(el, typ, getProps));
90+ }
91+
92+ function transformDate(val: any): any {
93+ if (val === null) {
94+ return null;
95+ }
96+ const d = new Date(val);
97+ if (isNaN(d.valueOf())) {
98+ return invalidValue(l("Date"), val, key, parent);
99+ }
100+ return d;
101+ }
102+
103+ function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
104+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
105+ return invalidValue(l(ref || "object"), val, key, parent);
106+ }
107+ const result: any = {};
108+ Object.getOwnPropertyNames(props).forEach(key => {
109+ const prop = props[key];
110+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
111+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
112+ });
113+ Object.getOwnPropertyNames(val).forEach(key => {
114+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
115+ result[key] = transform(val[key], additional, getProps, key, ref);
116+ }
117+ });
118+ return result;
119+ }
120+
121+ if (typ === "any") return val;
122+ if (typ === null) {
123+ if (val === null) return val;
124+ return invalidValue(typ, val, key, parent);
125+ }
126+ if (typ === false) return invalidValue(typ, val, key, parent);
127+ let ref: any = undefined;
128+ while (typeof typ === "object" && typ.ref !== undefined) {
129+ ref = typ.ref;
130+ typ = typeMap[typ.ref];
131+ }
132+ if (Array.isArray(typ)) return transformEnum(typ, val);
133+ if (typeof typ === "object") {
134+ return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
135+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
136+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
137+ : invalidValue(typ, val, key, parent);
138+ }
139+ // Numbers can be parsed by Date but shouldn't be.
140+ if (typ === Date && typeof val !== "number") return transformDate(val);
141+ return transformPrimitive(typ, val);
142+}
143+
144+function cast<T>(val: any, typ: any): T {
145+ return transform(val, typ, jsonToJSProps);
146+}
147+
148+function uncast<T>(val: T, typ: any): any {
149+ return transform(val, typ, jsToJSONProps);
150+}
151+
152+function l(typ: any) {
153+ return { literal: typ };
154+}
155+
156+function a(typ: any) {
157+ return { arrayItems: typ };
158+}
159+
160+function u(...typs: any[]) {
161+ return { unionMembers: typs };
162+}
163+
164+function o(props: any[], additional: any) {
165+ return { props, additional };
166+}
167+
168+function m(additional: any) {
169+ const props: any[] = [];
170+ return { props, additional };
171+}
172+
173+function r(name: string) {
174+ return { ref: name };
175+}
176+
177+const typeMap: any = {
178+};
Mschema-typescript/test/inputs/schema/union.schema/default/TopLevel.ts+8 −6
@@ -7,7 +7,9 @@
77 // These functions will throw an error if the JSON doesn't
88 // match the expected interface, even if the JSON is valid.
99
10-export interface TopLevel {
10+export type TopLevel = TopLevelElement[];
11+
12+export interface TopLevelElement {
1113 one?: number;
1214 two: boolean;
1315 three?: number;
@@ -17,12 +19,12 @@ export interface TopLevel {
1719 // Converts JSON strings to/from your types
1820 // and asserts the results of JSON.parse at runtime
1921 export class Convert {
20- public static toTopLevel(json: string): TopLevel[] {
21- return cast(JSON.parse(json), a(r("TopLevel")));
22+ public static toTopLevel(json: string): TopLevelElement[] {
23+ return cast(JSON.parse(json), a(r("TopLevelElement")));
2224 }
2325
24- public static topLevelToJson(value: TopLevel[]): string {
25- return JSON.stringify(uncast(value, a(r("TopLevel"))), null, 2);
26+ public static topLevelToJson(value: TopLevelElement[]): string {
27+ return JSON.stringify(uncast(value, a(r("TopLevelElement"))), null, 2);
2628 }
2729 }
2830
@@ -180,7 +182,7 @@ function r(name: string) {
180182 }
181183
182184 const typeMap: any = {
183- "TopLevel": o([
185+ "TopLevelElement": o([
184186 { json: "one", js: "one", typ: u(undefined, 0) },
185187 { json: "two", js: "two", typ: true },
186188 { json: "three", js: "three", typ: u(undefined, 3.14) },
No generated files match these filters.