Generated-output differences

quicktype output changed between the PR base and tested PR merge revisions.
← Back to the pull request
1test cases
40files differ
0modified
40new
0deleted
3,998changed lines
+3,998 −0insertions / deletions
Base a49b94e8f6f1b319a4da9fb15d57ef13ba316ddc · PR merge c7bbbe5650c573ef6b2d3f851d62e6f1b0d1a061 · Head bc0809f980c543fb0b473d44cc2c6f8ae89d6f7d · raw patch
Test case

test/inputs/schema/percent-encoded-ref.schema

40 generated files · +3,998 −0
Aschema-cplusplusdefault / quicktype.hpp+176 −0
@@ -0,0 +1,176 @@
1+// To parse this JSON data, first install
2+//
3+// json.hpp https://github.com/nlohmann/json
4+//
5+// Then include this file, and then do
6+//
7+// TopLevel data = nlohmann::json::parse(jsonString);
8+
9+#pragma once
10+
11+#include "json.hpp"
12+
13+#include <optional>
14+#include <stdexcept>
15+#include <regex>
16+
17+namespace quicktype {
18+ using nlohmann::json;
19+
20+ #ifndef NLOHMANN_UNTYPED_quicktype_HELPER
21+ #define NLOHMANN_UNTYPED_quicktype_HELPER
22+ inline json get_untyped(const json & j, const char * property) {
23+ if (j.find(property) != j.end()) {
24+ return j.at(property).get<json>();
25+ }
26+ return json();
27+ }
28+
29+ inline json get_untyped(const json & j, std::string property) {
30+ return get_untyped(j, property.data());
31+ }
32+ #endif
33+
34+ enum class FooState : int { XX, YY };
35+
36+ class StateInfoXxx {
37+ public:
38+ StateInfoXxx() = default;
39+ virtual ~StateInfoXxx() = default;
40+
41+ private:
42+ double change_time;
43+ FooState state;
44+
45+ public:
46+ const double & get_change_time() const { return change_time; }
47+ double & get_mutable_change_time() { return change_time; }
48+ void set_change_time(const double & value) { this->change_time = value; }
49+
50+ const FooState & get_state() const { return state; }
51+ FooState & get_mutable_state() { return state; }
52+ void set_state(const FooState & value) { this->state = value; }
53+ };
54+
55+ enum class WooState : int { ASD, QWE, ZXC, TYU };
56+
57+ class StateInfoWww {
58+ public:
59+ StateInfoWww() = default;
60+ virtual ~StateInfoWww() = default;
61+
62+ private:
63+ double change_time;
64+ WooState state;
65+
66+ public:
67+ const double & get_change_time() const { return change_time; }
68+ double & get_mutable_change_time() { return change_time; }
69+ void set_change_time(const double & value) { this->change_time = value; }
70+
71+ const WooState & get_state() const { return state; }
72+ WooState & get_mutable_state() { return state; }
73+ void set_state(const WooState & value) { this->state = value; }
74+ };
75+
76+ class TopLevel {
77+ public:
78+ TopLevel() = default;
79+ virtual ~TopLevel() = default;
80+
81+ private:
82+ StateInfoXxx foo;
83+ StateInfoWww woo;
84+
85+ public:
86+ const StateInfoXxx & get_foo() const { return foo; }
87+ StateInfoXxx & get_mutable_foo() { return foo; }
88+ void set_foo(const StateInfoXxx & value) { this->foo = value; }
89+
90+ const StateInfoWww & get_woo() const { return woo; }
91+ StateInfoWww & get_mutable_woo() { return woo; }
92+ void set_woo(const StateInfoWww & value) { this->woo = value; }
93+ };
94+}
95+
96+namespace quicktype {
97+ void from_json(const json & j, StateInfoXxx & x);
98+ void to_json(json & j, const StateInfoXxx & x);
99+
100+ void from_json(const json & j, StateInfoWww & x);
101+ void to_json(json & j, const StateInfoWww & x);
102+
103+ void from_json(const json & j, TopLevel & x);
104+ void to_json(json & j, const TopLevel & x);
105+
106+ void from_json(const json & j, FooState & x);
107+ void to_json(json & j, const FooState & x);
108+
109+ void from_json(const json & j, WooState & x);
110+ void to_json(json & j, const WooState & x);
111+
112+ inline void from_json(const json & j, StateInfoXxx& x) {
113+ x.set_change_time(j.at("changeTime").get<double>());
114+ x.set_state(j.at("state").get<FooState>());
115+ }
116+
117+ inline void to_json(json & j, const StateInfoXxx & x) {
118+ j = json::object();
119+ j["changeTime"] = x.get_change_time();
120+ j["state"] = x.get_state();
121+ }
122+
123+ inline void from_json(const json & j, StateInfoWww& x) {
124+ x.set_change_time(j.at("changeTime").get<double>());
125+ x.set_state(j.at("state").get<WooState>());
126+ }
127+
128+ inline void to_json(json & j, const StateInfoWww & x) {
129+ j = json::object();
130+ j["changeTime"] = x.get_change_time();
131+ j["state"] = x.get_state();
132+ }
133+
134+ inline void from_json(const json & j, TopLevel& x) {
135+ x.set_foo(j.at("foo").get<StateInfoXxx>());
136+ x.set_woo(j.at("woo").get<StateInfoWww>());
137+ }
138+
139+ inline void to_json(json & j, const TopLevel & x) {
140+ j = json::object();
141+ j["foo"] = x.get_foo();
142+ j["woo"] = x.get_woo();
143+ }
144+
145+ inline void from_json(const json & j, FooState & x) {
146+ if (j == "xx") x = FooState::XX;
147+ else if (j == "yy") x = FooState::YY;
148+ else { throw std::runtime_error("Cannot deserialize to enumeration \"FooState\""); }
149+ }
150+
151+ inline void to_json(json & j, const FooState & x) {
152+ switch (x) {
153+ case FooState::XX: j = "xx"; break;
154+ case FooState::YY: j = "yy"; break;
155+ default: throw std::runtime_error("Unexpected value in enumeration \"FooState\": " + std::to_string(static_cast<int>(x)));
156+ }
157+ }
158+
159+ inline void from_json(const json & j, WooState & x) {
160+ if (j == "asd") x = WooState::ASD;
161+ else if (j == "qwe") x = WooState::QWE;
162+ else if (j == "zxc") x = WooState::ZXC;
163+ else if (j == "tyu") x = WooState::TYU;
164+ else { throw std::runtime_error("Cannot deserialize to enumeration \"WooState\""); }
165+ }
166+
167+ inline void to_json(json & j, const WooState & x) {
168+ switch (x) {
169+ case WooState::ASD: j = "asd"; break;
170+ case WooState::QWE: j = "qwe"; break;
171+ case WooState::ZXC: j = "zxc"; break;
172+ case WooState::TYU: j = "tyu"; break;
173+ default: throw std::runtime_error("Unexpected value in enumeration \"WooState\": " + std::to_string(static_cast<int>(x)));
174+ }
175+ }
176+}
Aschema-csharp-recordsdefault / QuickType.cs+180 −0
@@ -0,0 +1,180 @@
1+// <auto-generated />
2+//
3+// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
4+//
5+// using QuickType;
6+//
7+// var topLevel = TopLevel.FromJson(jsonString);
8+#nullable enable
9+#pragma warning disable CS8618
10+#pragma warning disable CS8601
11+#pragma warning disable CS8602
12+#pragma warning disable CS8603
13+#pragma warning disable CS8604
14+#pragma warning disable CS8625
15+#pragma warning disable CS8765
16+
17+namespace QuickType
18+{
19+ using System;
20+ using System.Collections.Generic;
21+
22+ using System.Globalization;
23+ using Newtonsoft.Json;
24+ using Newtonsoft.Json.Converters;
25+
26+ public partial record TopLevel
27+ {
28+ [JsonProperty("foo", Required = Required.Always)]
29+ public StateInfoXxx Foo { get; set; }
30+
31+ [JsonProperty("woo", Required = Required.Always)]
32+ public StateInfoWww Woo { get; set; }
33+ }
34+
35+ public partial record StateInfoXxx
36+ {
37+ [JsonProperty("changeTime", Required = Required.Always)]
38+ public double ChangeTime { get; set; }
39+
40+ [JsonProperty("state", Required = Required.Always)]
41+ public FooState State { get; set; }
42+ }
43+
44+ public partial record StateInfoWww
45+ {
46+ [JsonProperty("changeTime", Required = Required.Always)]
47+ public double ChangeTime { get; set; }
48+
49+ [JsonProperty("state", Required = Required.Always)]
50+ public WooState State { get; set; }
51+ }
52+
53+ public enum FooState { Xx, Yy };
54+
55+ public enum WooState { Asd, Qwe, Zxc, Tyu };
56+
57+ public partial record TopLevel
58+ {
59+ public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings);
60+ }
61+
62+ public static partial class Serialize
63+ {
64+ public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
65+ }
66+
67+ internal static partial class Converter
68+ {
69+ public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
70+ {
71+ MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
72+ DateParseHandling = DateParseHandling.None,
73+ Converters =
74+ {
75+ FooStateConverter.Singleton,
76+ WooStateConverter.Singleton,
77+ new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
78+ },
79+ };
80+ }
81+
82+ internal class FooStateConverter : JsonConverter
83+ {
84+ public override bool CanConvert(Type t) => t == typeof(FooState) || t == typeof(FooState?);
85+
86+ public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
87+ {
88+ if (reader.TokenType == JsonToken.Null) return null;
89+ var value = serializer.Deserialize<string>(reader);
90+ switch (value)
91+ {
92+ case "xx":
93+ return FooState.Xx;
94+ case "yy":
95+ return FooState.Yy;
96+ }
97+ throw new Exception("Cannot unmarshal type FooState");
98+ }
99+
100+ public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
101+ {
102+ if (untypedValue == null)
103+ {
104+ serializer.Serialize(writer, null);
105+ return;
106+ }
107+ var value = (FooState)untypedValue;
108+ switch (value)
109+ {
110+ case FooState.Xx:
111+ serializer.Serialize(writer, "xx");
112+ return;
113+ case FooState.Yy:
114+ serializer.Serialize(writer, "yy");
115+ return;
116+ }
117+ throw new Exception("Cannot marshal type FooState");
118+ }
119+
120+ public static readonly FooStateConverter Singleton = new FooStateConverter();
121+ }
122+
123+ internal class WooStateConverter : JsonConverter
124+ {
125+ public override bool CanConvert(Type t) => t == typeof(WooState) || t == typeof(WooState?);
126+
127+ public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
128+ {
129+ if (reader.TokenType == JsonToken.Null) return null;
130+ var value = serializer.Deserialize<string>(reader);
131+ switch (value)
132+ {
133+ case "asd":
134+ return WooState.Asd;
135+ case "qwe":
136+ return WooState.Qwe;
137+ case "zxc":
138+ return WooState.Zxc;
139+ case "tyu":
140+ return WooState.Tyu;
141+ }
142+ throw new Exception("Cannot unmarshal type WooState");
143+ }
144+
145+ public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
146+ {
147+ if (untypedValue == null)
148+ {
149+ serializer.Serialize(writer, null);
150+ return;
151+ }
152+ var value = (WooState)untypedValue;
153+ switch (value)
154+ {
155+ case WooState.Asd:
156+ serializer.Serialize(writer, "asd");
157+ return;
158+ case WooState.Qwe:
159+ serializer.Serialize(writer, "qwe");
160+ return;
161+ case WooState.Zxc:
162+ serializer.Serialize(writer, "zxc");
163+ return;
164+ case WooState.Tyu:
165+ serializer.Serialize(writer, "tyu");
166+ return;
167+ }
168+ throw new Exception("Cannot marshal type WooState");
169+ }
170+
171+ public static readonly WooStateConverter Singleton = new WooStateConverter();
172+ }
173+}
174+#pragma warning restore CS8618
175+#pragma warning restore CS8601
176+#pragma warning restore CS8602
177+#pragma warning restore CS8603
178+#pragma warning restore CS8604
179+#pragma warning restore CS8625
180+#pragma warning restore CS8765
Aschema-csharp-SystemTextJsondefault / QuickType.cs+276 −0
@@ -0,0 +1,276 @@
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("foo")]
27+ public StateInfoXxx Foo { get; set; }
28+
29+ [JsonRequired]
30+ [JsonPropertyName("woo")]
31+ public StateInfoWww Woo { get; set; }
32+ }
33+
34+ public partial class StateInfoXxx
35+ {
36+ [JsonRequired]
37+ [JsonPropertyName("changeTime")]
38+ public double ChangeTime { get; set; }
39+
40+ [JsonRequired]
41+ [JsonPropertyName("state")]
42+ public FooState State { get; set; }
43+ }
44+
45+ public partial class StateInfoWww
46+ {
47+ [JsonRequired]
48+ [JsonPropertyName("changeTime")]
49+ public double ChangeTime { get; set; }
50+
51+ [JsonRequired]
52+ [JsonPropertyName("state")]
53+ public WooState State { get; set; }
54+ }
55+
56+ public enum FooState { Xx, Yy };
57+
58+ public enum WooState { Asd, Qwe, Zxc, Tyu };
59+
60+ public partial class TopLevel
61+ {
62+ public static TopLevel FromJson(string json) => JsonSerializer.Deserialize<TopLevel>(json, QuickType.Converter.Settings);
63+ }
64+
65+ public static partial class Serialize
66+ {
67+ public static string ToJson(this TopLevel self) => JsonSerializer.Serialize(self, QuickType.Converter.Settings);
68+ }
69+
70+ internal static partial class Converter
71+ {
72+ public static readonly JsonSerializerOptions Settings = new(JsonSerializerDefaults.General)
73+ {
74+ Converters =
75+ {
76+ FooStateConverter.Singleton,
77+ WooStateConverter.Singleton,
78+ new DateOnlyConverter(),
79+ new TimeOnlyConverter(),
80+ IsoDateTimeOffsetConverter.Singleton
81+ },
82+ };
83+ }
84+
85+ internal class FooStateConverter : JsonConverter<FooState>
86+ {
87+ public override bool CanConvert(Type t) => t == typeof(FooState);
88+
89+ public override FooState Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
90+ {
91+ var value = reader.GetString();
92+ switch (value)
93+ {
94+ case "xx":
95+ return FooState.Xx;
96+ case "yy":
97+ return FooState.Yy;
98+ }
99+ throw new JsonException("Cannot unmarshal type FooState");
100+ }
101+
102+ public override void Write(Utf8JsonWriter writer, FooState value, JsonSerializerOptions options)
103+ {
104+ switch (value)
105+ {
106+ case FooState.Xx:
107+ JsonSerializer.Serialize(writer, "xx", options);
108+ return;
109+ case FooState.Yy:
110+ JsonSerializer.Serialize(writer, "yy", options);
111+ return;
112+ }
113+ throw new NotSupportedException("Cannot marshal type FooState");
114+ }
115+
116+ public static readonly FooStateConverter Singleton = new FooStateConverter();
117+ }
118+
119+ internal class WooStateConverter : JsonConverter<WooState>
120+ {
121+ public override bool CanConvert(Type t) => t == typeof(WooState);
122+
123+ public override WooState Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
124+ {
125+ var value = reader.GetString();
126+ switch (value)
127+ {
128+ case "asd":
129+ return WooState.Asd;
130+ case "qwe":
131+ return WooState.Qwe;
132+ case "zxc":
133+ return WooState.Zxc;
134+ case "tyu":
135+ return WooState.Tyu;
136+ }
137+ throw new JsonException("Cannot unmarshal type WooState");
138+ }
139+
140+ public override void Write(Utf8JsonWriter writer, WooState value, JsonSerializerOptions options)
141+ {
142+ switch (value)
143+ {
144+ case WooState.Asd:
145+ JsonSerializer.Serialize(writer, "asd", options);
146+ return;
147+ case WooState.Qwe:
148+ JsonSerializer.Serialize(writer, "qwe", options);
149+ return;
150+ case WooState.Zxc:
151+ JsonSerializer.Serialize(writer, "zxc", options);
152+ return;
153+ case WooState.Tyu:
154+ JsonSerializer.Serialize(writer, "tyu", options);
155+ return;
156+ }
157+ throw new NotSupportedException("Cannot marshal type WooState");
158+ }
159+
160+ public static readonly WooStateConverter Singleton = new WooStateConverter();
161+ }
162+
163+ public class DateOnlyConverter : JsonConverter<DateOnly>
164+ {
165+ private readonly string serializationFormat;
166+ public DateOnlyConverter() : this(null) { }
167+
168+ public DateOnlyConverter(string? serializationFormat)
169+ {
170+ this.serializationFormat = serializationFormat ?? "yyyy-MM-dd";
171+ }
172+
173+ public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
174+ {
175+ var value = reader.GetString();
176+ return DateOnly.Parse(value!);
177+ }
178+
179+ public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
180+ => writer.WriteStringValue(value.ToString(serializationFormat));
181+ }
182+
183+ public class TimeOnlyConverter : JsonConverter<TimeOnly>
184+ {
185+ private readonly string serializationFormat;
186+
187+ public TimeOnlyConverter() : this(null) { }
188+
189+ public TimeOnlyConverter(string? serializationFormat)
190+ {
191+ this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff";
192+ }
193+
194+ public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
195+ {
196+ var value = reader.GetString();
197+ return TimeOnly.Parse(value!);
198+ }
199+
200+ public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options)
201+ => writer.WriteStringValue(value.ToString(serializationFormat));
202+ }
203+
204+ internal class IsoDateTimeOffsetConverter : JsonConverter<DateTimeOffset>
205+ {
206+ public override bool CanConvert(Type t) => t == typeof(DateTimeOffset);
207+
208+ private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
209+
210+ private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind;
211+ private string? _dateTimeFormat;
212+ private CultureInfo? _culture;
213+
214+ public DateTimeStyles DateTimeStyles
215+ {
216+ get => _dateTimeStyles;
217+ set => _dateTimeStyles = value;
218+ }
219+
220+ public string? DateTimeFormat
221+ {
222+ get => _dateTimeFormat ?? string.Empty;
223+ set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value;
224+ }
225+
226+ public CultureInfo Culture
227+ {
228+ get => _culture ?? CultureInfo.CurrentCulture;
229+ set => _culture = value;
230+ }
231+
232+ public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
233+ {
234+ string text;
235+
236+
237+ if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
238+ || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
239+ {
240+ value = value.ToUniversalTime();
241+ }
242+
243+ text = value.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
244+
245+ writer.WriteStringValue(text);
246+ }
247+
248+ public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
249+ {
250+ string? dateText = reader.GetString();
251+
252+ if (string.IsNullOrEmpty(dateText) == false)
253+ {
254+ if (!string.IsNullOrEmpty(_dateTimeFormat))
255+ {
256+ return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
257+ }
258+ else
259+ {
260+ return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles);
261+ }
262+ }
263+ else
264+ {
265+ return default(DateTimeOffset);
266+ }
267+ }
268+
269+
270+ public static readonly IsoDateTimeOffsetConverter Singleton = new IsoDateTimeOffsetConverter();
271+ }
272+}
273+#pragma warning restore CS8618
274+#pragma warning restore CS8601
275+#pragma warning restore CS8602
276+#pragma warning restore CS8603
Aschema-csharpdefault / QuickType.cs+180 −0
@@ -0,0 +1,180 @@
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("foo", Required = Required.Always)]
29+ public StateInfoXxx Foo { get; set; }
30+
31+ [JsonProperty("woo", Required = Required.Always)]
32+ public StateInfoWww Woo { get; set; }
33+ }
34+
35+ public partial class StateInfoXxx
36+ {
37+ [JsonProperty("changeTime", Required = Required.Always)]
38+ public double ChangeTime { get; set; }
39+
40+ [JsonProperty("state", Required = Required.Always)]
41+ public FooState State { get; set; }
42+ }
43+
44+ public partial class StateInfoWww
45+ {
46+ [JsonProperty("changeTime", Required = Required.Always)]
47+ public double ChangeTime { get; set; }
48+
49+ [JsonProperty("state", Required = Required.Always)]
50+ public WooState State { get; set; }
51+ }
52+
53+ public enum FooState { Xx, Yy };
54+
55+ public enum WooState { Asd, Qwe, Zxc, Tyu };
56+
57+ public partial class TopLevel
58+ {
59+ public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings);
60+ }
61+
62+ public static partial class Serialize
63+ {
64+ public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
65+ }
66+
67+ internal static partial class Converter
68+ {
69+ public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
70+ {
71+ MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
72+ DateParseHandling = DateParseHandling.None,
73+ Converters =
74+ {
75+ FooStateConverter.Singleton,
76+ WooStateConverter.Singleton,
77+ new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
78+ },
79+ };
80+ }
81+
82+ internal class FooStateConverter : JsonConverter
83+ {
84+ public override bool CanConvert(Type t) => t == typeof(FooState) || t == typeof(FooState?);
85+
86+ public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
87+ {
88+ if (reader.TokenType == JsonToken.Null) return null;
89+ var value = serializer.Deserialize<string>(reader);
90+ switch (value)
91+ {
92+ case "xx":
93+ return FooState.Xx;
94+ case "yy":
95+ return FooState.Yy;
96+ }
97+ throw new Exception("Cannot unmarshal type FooState");
98+ }
99+
100+ public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
101+ {
102+ if (untypedValue == null)
103+ {
104+ serializer.Serialize(writer, null);
105+ return;
106+ }
107+ var value = (FooState)untypedValue;
108+ switch (value)
109+ {
110+ case FooState.Xx:
111+ serializer.Serialize(writer, "xx");
112+ return;
113+ case FooState.Yy:
114+ serializer.Serialize(writer, "yy");
115+ return;
116+ }
117+ throw new Exception("Cannot marshal type FooState");
118+ }
119+
120+ public static readonly FooStateConverter Singleton = new FooStateConverter();
121+ }
122+
123+ internal class WooStateConverter : JsonConverter
124+ {
125+ public override bool CanConvert(Type t) => t == typeof(WooState) || t == typeof(WooState?);
126+
127+ public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
128+ {
129+ if (reader.TokenType == JsonToken.Null) return null;
130+ var value = serializer.Deserialize<string>(reader);
131+ switch (value)
132+ {
133+ case "asd":
134+ return WooState.Asd;
135+ case "qwe":
136+ return WooState.Qwe;
137+ case "zxc":
138+ return WooState.Zxc;
139+ case "tyu":
140+ return WooState.Tyu;
141+ }
142+ throw new Exception("Cannot unmarshal type WooState");
143+ }
144+
145+ public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
146+ {
147+ if (untypedValue == null)
148+ {
149+ serializer.Serialize(writer, null);
150+ return;
151+ }
152+ var value = (WooState)untypedValue;
153+ switch (value)
154+ {
155+ case WooState.Asd:
156+ serializer.Serialize(writer, "asd");
157+ return;
158+ case WooState.Qwe:
159+ serializer.Serialize(writer, "qwe");
160+ return;
161+ case WooState.Zxc:
162+ serializer.Serialize(writer, "zxc");
163+ return;
164+ case WooState.Tyu:
165+ serializer.Serialize(writer, "tyu");
166+ return;
167+ }
168+ throw new Exception("Cannot marshal type WooState");
169+ }
170+
171+ public static readonly WooStateConverter Singleton = new WooStateConverter();
172+ }
173+}
174+#pragma warning restore CS8618
175+#pragma warning restore CS8601
176+#pragma warning restore CS8602
177+#pragma warning restore CS8603
178+#pragma warning restore CS8604
179+#pragma warning restore CS8625
180+#pragma warning restore CS8765
Aschema-dartdefault / TopLevel.dart+105 −0
@@ -0,0 +1,105 @@
1+// To parse this JSON data, do
2+//
3+// final topLevel = topLevelFromJson(jsonString);
4+
5+import 'dart:convert';
6+
7+TopLevel topLevelFromJson(String str) => TopLevel.fromJson(json.decode(str));
8+
9+String topLevelToJson(TopLevel data) => json.encode(data.toJson());
10+
11+class TopLevel {
12+ final StateInfoXxx foo;
13+ final StateInfoWww woo;
14+
15+ TopLevel({
16+ required this.foo,
17+ required this.woo,
18+ });
19+
20+ factory TopLevel.fromJson(Map<String, dynamic> json) => TopLevel(
21+ foo: StateInfoXxx.fromJson(json["foo"]),
22+ woo: StateInfoWww.fromJson(json["woo"]),
23+ );
24+
25+ Map<String, dynamic> toJson() => {
26+ "foo": foo.toJson(),
27+ "woo": woo.toJson(),
28+ };
29+}
30+
31+class StateInfoXxx {
32+ final double changeTime;
33+ final FooState state;
34+
35+ StateInfoXxx({
36+ required this.changeTime,
37+ required this.state,
38+ });
39+
40+ factory StateInfoXxx.fromJson(Map<String, dynamic> json) => StateInfoXxx(
41+ changeTime: json["changeTime"]?.toDouble(),
42+ state: fooStateValues.map[json["state"]]!,
43+ );
44+
45+ Map<String, dynamic> toJson() => {
46+ "changeTime": changeTime,
47+ "state": fooStateValues.reverse[state],
48+ };
49+}
50+
51+enum FooState {
52+ XX,
53+ YY
54+}
55+
56+final fooStateValues = EnumValues({
57+ "xx": FooState.XX,
58+ "yy": FooState.YY
59+});
60+
61+class StateInfoWww {
62+ final double changeTime;
63+ final WooState state;
64+
65+ StateInfoWww({
66+ required this.changeTime,
67+ required this.state,
68+ });
69+
70+ factory StateInfoWww.fromJson(Map<String, dynamic> json) => StateInfoWww(
71+ changeTime: json["changeTime"]?.toDouble(),
72+ state: wooStateValues.map[json["state"]]!,
73+ );
74+
75+ Map<String, dynamic> toJson() => {
76+ "changeTime": changeTime,
77+ "state": wooStateValues.reverse[state],
78+ };
79+}
80+
81+enum WooState {
82+ ASD,
83+ QWE,
84+ ZXC,
85+ TYU
86+}
87+
88+final wooStateValues = EnumValues({
89+ "asd": WooState.ASD,
90+ "qwe": WooState.QWE,
91+ "zxc": WooState.ZXC,
92+ "tyu": WooState.TYU
93+});
94+
95+class EnumValues<T> {
96+ Map<String, T> map;
97+ late Map<T, String> reverseMap;
98+
99+ EnumValues(this.map);
100+
101+ Map<T, String> get reverse {
102+ reverseMap = map.map((k, v) => MapEntry(v, k));
103+ return reverseMap;
104+ }
105+}
Aschema-elixirdefault / QuickType.ex+208 −0
@@ -0,0 +1,208 @@
1+# This file was autogenerated using quicktype https://github.com/quicktype/quicktype
2+#
3+# Add Jason to your mix.exs
4+#
5+# Decode a JSON string: TopLevel.from_json(data)
6+# Encode into a JSON string: TopLevel.to_json(struct)
7+
8+defmodule FooState do
9+ @valid_enum_members [
10+ :xx,
11+ :yy,
12+ ]
13+
14+ def valid_atom?(value), do: value in @valid_enum_members
15+
16+ def valid_atom_string?(value) do
17+ try do
18+ atom = String.to_existing_atom(value)
19+ atom in @valid_enum_members
20+ rescue
21+ ArgumentError -> false
22+ end
23+ end
24+
25+ def encode(value) do
26+ if valid_atom?(value) do
27+ Atom.to_string(value)
28+ else
29+ {:error, "Unexpected value when encoding atom: #{inspect(value)}"}
30+ end
31+ end
32+
33+ def decode(value) do
34+ if valid_atom_string?(value) do
35+ String.to_existing_atom(value)
36+ else
37+ {:error, "Unexpected value when decoding atom: #{inspect(value)}"}
38+ end
39+ end
40+
41+ def from_json(json) do
42+ json
43+ |> Jason.decode!()
44+ |> decode()
45+ end
46+
47+ def to_json(data) do
48+ data
49+ |> encode()
50+ |> Jason.encode!()
51+ end
52+end
53+
54+defmodule StateInfoXxx do
55+ @enforce_keys [:change_time, :state]
56+ defstruct [:change_time, :state]
57+
58+ @type t :: %__MODULE__{
59+ change_time: float(),
60+ state: FooState.t()
61+ }
62+
63+ def from_map(m) do
64+ %StateInfoXxx{
65+ change_time: m["changeTime"],
66+ state: FooState.decode(m["state"]),
67+ }
68+ end
69+
70+ def from_json(json) do
71+ json
72+ |> Jason.decode!()
73+ |> from_map()
74+ end
75+
76+ def to_map(struct) do
77+ %{
78+ "changeTime" => struct.change_time,
79+ "state" => FooState.encode(struct.state),
80+ }
81+ end
82+
83+ def to_json(struct) do
84+ struct
85+ |> to_map()
86+ |> Jason.encode!()
87+ end
88+end
89+
90+defmodule WooState do
91+ @valid_enum_members [
92+ :asd,
93+ :qwe,
94+ :zxc,
95+ :tyu,
96+ ]
97+
98+ def valid_atom?(value), do: value in @valid_enum_members
99+
100+ def valid_atom_string?(value) do
101+ try do
102+ atom = String.to_existing_atom(value)
103+ atom in @valid_enum_members
104+ rescue
105+ ArgumentError -> false
106+ end
107+ end
108+
109+ def encode(value) do
110+ if valid_atom?(value) do
111+ Atom.to_string(value)
112+ else
113+ {:error, "Unexpected value when encoding atom: #{inspect(value)}"}
114+ end
115+ end
116+
117+ def decode(value) do
118+ if valid_atom_string?(value) do
119+ String.to_existing_atom(value)
120+ else
121+ {:error, "Unexpected value when decoding atom: #{inspect(value)}"}
122+ end
123+ end
124+
125+ def from_json(json) do
126+ json
127+ |> Jason.decode!()
128+ |> decode()
129+ end
130+
131+ def to_json(data) do
132+ data
133+ |> encode()
134+ |> Jason.encode!()
135+ end
136+end
137+
138+defmodule StateInfoWWW do
139+ @enforce_keys [:change_time, :state]
140+ defstruct [:change_time, :state]
141+
142+ @type t :: %__MODULE__{
143+ change_time: float(),
144+ state: WooState.t()
145+ }
146+
147+ def from_map(m) do
148+ %StateInfoWWW{
149+ change_time: m["changeTime"],
150+ state: WooState.decode(m["state"]),
151+ }
152+ end
153+
154+ def from_json(json) do
155+ json
156+ |> Jason.decode!()
157+ |> from_map()
158+ end
159+
160+ def to_map(struct) do
161+ %{
162+ "changeTime" => struct.change_time,
163+ "state" => WooState.encode(struct.state),
164+ }
165+ end
166+
167+ def to_json(struct) do
168+ struct
169+ |> to_map()
170+ |> Jason.encode!()
171+ end
172+end
173+
174+defmodule TopLevel do
175+ @enforce_keys [:foo, :woo]
176+ defstruct [:foo, :woo]
177+
178+ @type t :: %__MODULE__{
179+ foo: StateInfoXxx.t(),
180+ woo: StateInfoWWW.t()
181+ }
182+
183+ def from_map(m) do
184+ %TopLevel{
185+ foo: StateInfoXxx.from_map(m["foo"]),
186+ woo: StateInfoWWW.from_map(m["woo"]),
187+ }
188+ end
189+
190+ def from_json(json) do
191+ json
192+ |> Jason.decode!()
193+ |> from_map()
194+ end
195+
196+ def to_map(struct) do
197+ %{
198+ "foo" => StateInfoXxx.to_map(struct.foo),
199+ "woo" => StateInfoWWW.to_map(struct.woo),
200+ }
201+ end
202+
203+ def to_json(struct) do
204+ struct
205+ |> to_map()
206+ |> Jason.encode!()
207+ end
208+end
Aschema-elmdefault / QuickType.elm+138 −0
@@ -0,0 +1,138 @@
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+ , StateInfoXxx
19+ , StateInfoWWW
20+ , FooState(..)
21+ , WooState(..)
22+ )
23+
24+import Json.Decode as Jdec
25+import Json.Decode.Pipeline as Jpipe
26+import Json.Encode as Jenc
27+import Dict exposing (Dict)
28+
29+type alias QuickType =
30+ { foo : StateInfoXxx
31+ , woo : StateInfoWWW
32+ }
33+
34+type alias StateInfoXxx =
35+ { changeTime : Float
36+ , state : FooState
37+ }
38+
39+type FooState
40+ = Xx
41+ | Yy
42+
43+type alias StateInfoWWW =
44+ { changeTime : Float
45+ , state : WooState
46+ }
47+
48+type WooState
49+ = Asd
50+ | Qwe
51+ | Zxc
52+ | Tyu
53+
54+-- decoders and encoders
55+
56+quickTypeToString : QuickType -> String
57+quickTypeToString r = Jenc.encode 0 (encodeQuickType r)
58+
59+quickType : Jdec.Decoder QuickType
60+quickType =
61+ Jdec.succeed QuickType
62+ |> Jpipe.required "foo" stateInfoXxx
63+ |> Jpipe.required "woo" stateInfoWWW
64+
65+encodeQuickType : QuickType -> Jenc.Value
66+encodeQuickType x =
67+ Jenc.object
68+ [ ("foo", encodeStateInfoXxx x.foo)
69+ , ("woo", encodeStateInfoWWW x.woo)
70+ ]
71+
72+stateInfoXxx : Jdec.Decoder StateInfoXxx
73+stateInfoXxx =
74+ Jdec.succeed StateInfoXxx
75+ |> Jpipe.required "changeTime" Jdec.float
76+ |> Jpipe.required "state" fooState
77+
78+encodeStateInfoXxx : StateInfoXxx -> Jenc.Value
79+encodeStateInfoXxx x =
80+ Jenc.object
81+ [ ("changeTime", Jenc.float x.changeTime)
82+ , ("state", encodeFooState x.state)
83+ ]
84+
85+fooState : Jdec.Decoder FooState
86+fooState =
87+ Jdec.string
88+ |> Jdec.andThen (\str ->
89+ case str of
90+ "xx" -> Jdec.succeed Xx
91+ "yy" -> Jdec.succeed Yy
92+ somethingElse -> Jdec.fail <| "Invalid FooState: " ++ somethingElse
93+ )
94+
95+encodeFooState : FooState -> Jenc.Value
96+encodeFooState x = case x of
97+ Xx -> Jenc.string "xx"
98+ Yy -> Jenc.string "yy"
99+
100+stateInfoWWW : Jdec.Decoder StateInfoWWW
101+stateInfoWWW =
102+ Jdec.succeed StateInfoWWW
103+ |> Jpipe.required "changeTime" Jdec.float
104+ |> Jpipe.required "state" wooState
105+
106+encodeStateInfoWWW : StateInfoWWW -> Jenc.Value
107+encodeStateInfoWWW x =
108+ Jenc.object
109+ [ ("changeTime", Jenc.float x.changeTime)
110+ , ("state", encodeWooState x.state)
111+ ]
112+
113+wooState : Jdec.Decoder WooState
114+wooState =
115+ Jdec.string
116+ |> Jdec.andThen (\str ->
117+ case str of
118+ "asd" -> Jdec.succeed Asd
119+ "qwe" -> Jdec.succeed Qwe
120+ "zxc" -> Jdec.succeed Zxc
121+ "tyu" -> Jdec.succeed Tyu
122+ somethingElse -> Jdec.fail <| "Invalid WooState: " ++ somethingElse
123+ )
124+
125+encodeWooState : WooState -> Jenc.Value
126+encodeWooState x = case x of
127+ Asd -> Jenc.string "asd"
128+ Qwe -> Jenc.string "qwe"
129+ Zxc -> Jenc.string "zxc"
130+ Tyu -> Jenc.string "tyu"
131+
132+--- encoder helpers
133+
134+makeNullableEncoder : (a -> Jenc.Value) -> Maybe a -> Jenc.Value
135+makeNullableEncoder f m =
136+ case m of
137+ Just x -> f x
138+ Nothing -> Jenc.null
Aschema-flowdefault / TopLevel.js+228 −0
@@ -0,0 +1,228 @@
1+// @flow
2+
3+// To parse this data:
4+//
5+// const Convert = require("./TopLevel");
6+//
7+// const topLevel = Convert.toTopLevel(json);
8+//
9+// These functions will throw an error if the JSON doesn't
10+// match the expected interface, even if the JSON is valid.
11+
12+export type TopLevel = {
13+ foo: StateInfoXxx;
14+ woo: StateInfoWWW;
15+};
16+
17+export type StateInfoXxx = {
18+ changeTime: number;
19+ state: FooState;
20+};
21+
22+export type FooState =
23+ "xx"
24+ | "yy";
25+
26+export type StateInfoWWW = {
27+ changeTime: number;
28+ state: WooState;
29+};
30+
31+export type WooState =
32+ "asd"
33+ | "qwe"
34+ | "zxc"
35+ | "tyu";
36+
37+// Converts JSON strings to/from your types
38+// and asserts the results of JSON.parse at runtime
39+function toTopLevel(json: string): TopLevel {
40+ return cast(JSON.parse(json), r("TopLevel"));
41+}
42+
43+function topLevelToJson(value: TopLevel): string {
44+ return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
45+}
46+
47+function invalidValue(typ: any, val: any, key: any, parent: any = '') {
48+ const prettyTyp = prettyTypeName(typ);
49+ const parentText = parent ? ` on ${parent}` : '';
50+ const keyText = key ? ` for key "${key}"` : '';
51+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
52+}
53+
54+function prettyTypeName(typ: any): string {
55+ if (Array.isArray(typ)) {
56+ if (typ.length === 2 && typ[0] === undefined) {
57+ return `an optional ${prettyTypeName(typ[1])}`;
58+ } else {
59+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
60+ }
61+ } else if (typeof typ === "object" && typ.literal !== undefined) {
62+ return typ.literal;
63+ } else {
64+ return typeof typ;
65+ }
66+}
67+
68+function jsonToJSProps(typ: any): any {
69+ if (typ.jsonToJS === undefined) {
70+ const map: any = {};
71+ typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
72+ typ.jsonToJS = map;
73+ }
74+ return typ.jsonToJS;
75+}
76+
77+function jsToJSONProps(typ: any): any {
78+ if (typ.jsToJSON === undefined) {
79+ const map: any = {};
80+ typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
81+ typ.jsToJSON = map;
82+ }
83+ return typ.jsToJSON;
84+}
85+
86+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
87+ function transformPrimitive(typ: string, val: any): any {
88+ if (typeof typ === typeof val) return val;
89+ return invalidValue(typ, val, key, parent);
90+ }
91+
92+ function transformUnion(typs: any[], val: any): any {
93+ // val must validate against one typ in typs
94+ const l = typs.length;
95+ for (let i = 0; i < l; i++) {
96+ const typ = typs[i];
97+ try {
98+ return transform(val, typ, getProps);
99+ } catch (_) {}
100+ }
101+ return invalidValue(typs, val, key, parent);
102+ }
103+
104+ function transformEnum(cases: string[], val: any): any {
105+ if (cases.indexOf(val) !== -1) return val;
106+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
107+ }
108+
109+ function transformArray(typ: any, val: any): any {
110+ // val must be an array with no invalid elements
111+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
112+ return val.map(el => transform(el, typ, getProps));
113+ }
114+
115+ function transformDate(val: any): any {
116+ if (val === null) {
117+ return null;
118+ }
119+ const d = new Date(val);
120+ if (isNaN(d.valueOf())) {
121+ return invalidValue(l("Date"), val, key, parent);
122+ }
123+ return d;
124+ }
125+
126+ function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
127+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
128+ return invalidValue(l(ref || "object"), val, key, parent);
129+ }
130+ const result: any = {};
131+ Object.getOwnPropertyNames(props).forEach(key => {
132+ const prop = props[key];
133+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
134+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
135+ });
136+ Object.getOwnPropertyNames(val).forEach(key => {
137+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
138+ result[key] = transform(val[key], additional, getProps, key, ref);
139+ }
140+ });
141+ return result;
142+ }
143+
144+ if (typ === "any") return val;
145+ if (typ === null) {
146+ if (val === null) return val;
147+ return invalidValue(typ, val, key, parent);
148+ }
149+ if (typ === false) return invalidValue(typ, val, key, parent);
150+ let ref: any = undefined;
151+ while (typeof typ === "object" && typ.ref !== undefined) {
152+ ref = typ.ref;
153+ typ = typeMap[typ.ref];
154+ }
155+ if (Array.isArray(typ)) return transformEnum(typ, val);
156+ if (typeof typ === "object") {
157+ return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
158+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
159+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
160+ : invalidValue(typ, val, key, parent);
161+ }
162+ // Numbers can be parsed by Date but shouldn't be.
163+ if (typ === Date && typeof val !== "number") return transformDate(val);
164+ return transformPrimitive(typ, val);
165+}
166+
167+function cast<T>(val: any, typ: any): T {
168+ return transform(val, typ, jsonToJSProps);
169+}
170+
171+function uncast<T>(val: T, typ: any): any {
172+ return transform(val, typ, jsToJSONProps);
173+}
174+
175+function l(typ: any) {
176+ return { literal: typ };
177+}
178+
179+function a(typ: any) {
180+ return { arrayItems: typ };
181+}
182+
183+function u(...typs: any[]) {
184+ return { unionMembers: typs };
185+}
186+
187+function o(props: any[], additional: any) {
188+ return { props, additional };
189+}
190+
191+function m(additional: any) {
192+ const props: any[] = [];
193+ return { props, additional };
194+}
195+
196+function r(name: string) {
197+ return { ref: name };
198+}
199+
200+const typeMap: any = {
201+ "TopLevel": o([
202+ { json: "foo", js: "foo", typ: r("StateInfoXxx") },
203+ { json: "woo", js: "woo", typ: r("StateInfoWWW") },
204+ ], false),
205+ "StateInfoXxx": o([
206+ { json: "changeTime", js: "changeTime", typ: 3.14 },
207+ { json: "state", js: "state", typ: r("FooState") },
208+ ], false),
209+ "StateInfoWWW": o([
210+ { json: "changeTime", js: "changeTime", typ: 3.14 },
211+ { json: "state", js: "state", typ: r("WooState") },
212+ ], false),
213+ "FooState": [
214+ "xx",
215+ "yy",
216+ ],
217+ "WooState": [
218+ "asd",
219+ "qwe",
220+ "zxc",
221+ "tyu",
222+ ],
223+};
224+
225+module.exports = {
226+ "topLevelToJson": topLevelToJson,
227+ "toTopLevel": toTopLevel,
228+};
Aschema-golangdefault / quicktype.go+50 −0
@@ -0,0 +1,50 @@
1+// Code generated from JSON Schema using quicktype. DO NOT EDIT.
2+// To parse and unparse this JSON data, add this code to your project and do:
3+//
4+// topLevel, err := UnmarshalTopLevel(bytes)
5+// bytes, err = topLevel.Marshal()
6+
7+package main
8+
9+import "encoding/json"
10+
11+func UnmarshalTopLevel(data []byte) (TopLevel, error) {
12+ var r TopLevel
13+ err := json.Unmarshal(data, &r)
14+ return r, err
15+}
16+
17+func (r *TopLevel) Marshal() ([]byte, error) {
18+ return json.Marshal(r)
19+}
20+
21+type TopLevel struct {
22+ Foo StateInfoXxx `json:"foo"`
23+ Woo StateInfoWWW `json:"woo"`
24+}
25+
26+type StateInfoXxx struct {
27+ ChangeTime float64 `json:"changeTime"`
28+ State FooState `json:"state"`
29+}
30+
31+type StateInfoWWW struct {
32+ ChangeTime float64 `json:"changeTime"`
33+ State WooState `json:"state"`
34+}
35+
36+type FooState string
37+
38+const (
39+ Xx FooState = "xx"
40+ Yy FooState = "yy"
41+)
42+
43+type WooState string
44+
45+const (
46+ Asd WooState = "asd"
47+ Qwe WooState = "qwe"
48+ Zxc WooState = "zxc"
49+ Tyu WooState = "tyu"
50+)
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / Converter.java+121 −0
@@ -0,0 +1,121 @@
1+// To use this code, add the following Maven dependency to your project:
2+//
3+//
4+// com.fasterxml.jackson.core : jackson-databind : 2.9.0
5+//
6+//
7+// Import this package:
8+//
9+// import io.quicktype.Converter;
10+//
11+// Then you can deserialize a JSON string with
12+//
13+// TopLevel data = Converter.fromJsonString(jsonString);
14+
15+package io.quicktype;
16+
17+import java.io.IOException;
18+import com.fasterxml.jackson.databind.*;
19+import com.fasterxml.jackson.databind.module.SimpleModule;
20+import com.fasterxml.jackson.core.JsonParser;
21+import com.fasterxml.jackson.core.JsonProcessingException;
22+import java.util.*;
23+import java.util.Date;
24+import java.text.SimpleDateFormat;
25+
26+public class Converter {
27+ // Date-time helpers
28+
29+ private static final String[] DATE_TIME_FORMATS = {
30+ "yyyy-MM-dd'T'HH:mm:ss.SX",
31+ "yyyy-MM-dd'T'HH:mm:ss.S",
32+ "yyyy-MM-dd'T'HH:mm:ssX",
33+ "yyyy-MM-dd'T'HH:mm:ss",
34+ "yyyy-MM-dd HH:mm:ss.SX",
35+ "yyyy-MM-dd HH:mm:ss.S",
36+ "yyyy-MM-dd HH:mm:ssX",
37+ "yyyy-MM-dd HH:mm:ss",
38+ "HH:mm:ss.SZ",
39+ "HH:mm:ss.S",
40+ "HH:mm:ssZ",
41+ "HH:mm:ss",
42+ "yyyy-MM-dd",
43+ };
44+
45+ public static Date parseAllDateTimeString(String str) {
46+ for (String format : DATE_TIME_FORMATS) {
47+ try {
48+ return new SimpleDateFormat(format).parse(str);
49+ } catch (Exception ex) {
50+ // Ignored
51+ }
52+ }
53+ return null;
54+ }
55+
56+ public static String serializeDateTime(Date datetime) {
57+ return new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ").format(datetime);
58+ }
59+
60+ public static String serializeDate(Date datetime) {
61+ return new SimpleDateFormat("yyyy-MM-dd").format(datetime);
62+ }
63+
64+ public static String serializeTime(Date datetime) {
65+ return new SimpleDateFormat("hh:mm:ssZ").format(datetime);
66+ }
67+ // Serialize/deserialize helpers
68+
69+ public static TopLevel fromJsonString(String json) throws IOException {
70+ return getObjectReader().readValue(json);
71+ }
72+
73+ public static String toJsonString(TopLevel obj) throws JsonProcessingException {
74+ return getObjectWriter().writeValueAsString(obj);
75+ }
76+
77+ private static ObjectReader reader;
78+ private static ObjectWriter writer;
79+
80+ private static void instantiateMapper() {
81+ ObjectMapper mapper = new ObjectMapper();
82+ mapper.findAndRegisterModules();
83+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
84+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
85+ SimpleModule module = new SimpleModule();
86+ module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
87+ @Override
88+ public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
89+ String value = jsonParser.getText();
90+ return Converter.parseAllDateTimeString(value);
91+ }
92+ });
93+ module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
94+ @Override
95+ public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
96+ String value = jsonParser.getText();
97+ return Converter.parseAllDateTimeString(value);
98+ }
99+ });
100+ module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
101+ @Override
102+ public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
103+ String value = jsonParser.getText();
104+ return Converter.parseAllDateTimeString(value);
105+ }
106+ });
107+ mapper.registerModule(module);
108+ reader = mapper.readerFor(TopLevel.class);
109+ writer = mapper.writerFor(TopLevel.class);
110+ }
111+
112+ private static ObjectReader getObjectReader() {
113+ if (reader == null) instantiateMapper();
114+ return reader;
115+ }
116+
117+ private static ObjectWriter getObjectWriter() {
118+ if (writer == null) instantiateMapper();
119+ return writer;
120+ }
121+}
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / FooState.java+24 −0
@@ -0,0 +1,24 @@
1+package io.quicktype;
2+
3+import java.io.IOException;
4+import com.fasterxml.jackson.annotation.*;
5+
6+public enum FooState {
7+ XX, YY;
8+
9+ @JsonValue
10+ public String toValue() {
11+ switch (this) {
12+ case XX: return "xx";
13+ case YY: return "yy";
14+ }
15+ return null;
16+ }
17+
18+ @JsonCreator
19+ public static FooState forValue(String value) throws IOException {
20+ if (value.equals("xx")) return XX;
21+ if (value.equals("yy")) return YY;
22+ throw new IOException("Cannot deserialize FooState");
23+ }
24+}
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / StateInfoWWW.java+18 −0
@@ -0,0 +1,18 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class StateInfoWWW {
6+ private double changeTime;
7+ private WooState state;
8+
9+ @JsonProperty("changeTime")
10+ public double getChangeTime() { return changeTime; }
11+ @JsonProperty("changeTime")
12+ public void setChangeTime(double value) { this.changeTime = value; }
13+
14+ @JsonProperty("state")
15+ public WooState getState() { return state; }
16+ @JsonProperty("state")
17+ public void setState(WooState value) { this.state = value; }
18+}
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / StateInfoXxx.java+18 −0
@@ -0,0 +1,18 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class StateInfoXxx {
6+ private double changeTime;
7+ private FooState state;
8+
9+ @JsonProperty("changeTime")
10+ public double getChangeTime() { return changeTime; }
11+ @JsonProperty("changeTime")
12+ public void setChangeTime(double value) { this.changeTime = value; }
13+
14+ @JsonProperty("state")
15+ public FooState getState() { return state; }
16+ @JsonProperty("state")
17+ public void setState(FooState value) { this.state = value; }
18+}
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / TopLevel.java+18 −0
@@ -0,0 +1,18 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class TopLevel {
6+ private StateInfoXxx foo;
7+ private StateInfoWWW woo;
8+
9+ @JsonProperty("foo")
10+ public StateInfoXxx getFoo() { return foo; }
11+ @JsonProperty("foo")
12+ public void setFoo(StateInfoXxx value) { this.foo = value; }
13+
14+ @JsonProperty("woo")
15+ public StateInfoWWW getWoo() { return woo; }
16+ @JsonProperty("woo")
17+ public void setWoo(StateInfoWWW value) { this.woo = value; }
18+}
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / WooState.java+28 −0
@@ -0,0 +1,28 @@
1+package io.quicktype;
2+
3+import java.io.IOException;
4+import com.fasterxml.jackson.annotation.*;
5+
6+public enum WooState {
7+ ASD, QWE, ZXC, TYU;
8+
9+ @JsonValue
10+ public String toValue() {
11+ switch (this) {
12+ case ASD: return "asd";
13+ case QWE: return "qwe";
14+ case ZXC: return "zxc";
15+ case TYU: return "tyu";
16+ }
17+ return null;
18+ }
19+
20+ @JsonCreator
21+ public static WooState forValue(String value) throws IOException {
22+ if (value.equals("asd")) return ASD;
23+ if (value.equals("qwe")) return QWE;
24+ if (value.equals("zxc")) return ZXC;
25+ if (value.equals("tyu")) return TYU;
26+ throw new IOException("Cannot deserialize WooState");
27+ }
28+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / Converter.java+101 −0
@@ -0,0 +1,101 @@
1+// To use this code, add the following Maven dependency to your project:
2+//
3+//
4+// com.fasterxml.jackson.core : jackson-databind : 2.9.0
5+// com.fasterxml.jackson.datatype : jackson-datatype-jsr310 : 2.9.0
6+//
7+// Import this package:
8+//
9+// import io.quicktype.Converter;
10+//
11+// Then you can deserialize a JSON string with
12+//
13+// TopLevel data = Converter.fromJsonString(jsonString);
14+
15+package io.quicktype;
16+
17+import java.io.IOException;
18+import com.fasterxml.jackson.databind.*;
19+import com.fasterxml.jackson.databind.module.SimpleModule;
20+import com.fasterxml.jackson.core.JsonParser;
21+import com.fasterxml.jackson.core.JsonProcessingException;
22+import java.util.*;
23+import java.time.LocalDate;
24+import java.time.OffsetDateTime;
25+import java.time.OffsetTime;
26+import java.time.ZoneOffset;
27+import java.time.ZonedDateTime;
28+import java.time.format.DateTimeFormatter;
29+import java.time.format.DateTimeFormatterBuilder;
30+import java.time.temporal.ChronoField;
31+
32+public class Converter {
33+ // Date-time helpers
34+
35+ private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
36+ .appendOptional(DateTimeFormatter.ISO_DATE_TIME)
37+ .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
38+ .appendOptional(DateTimeFormatter.ISO_INSTANT)
39+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX"))
40+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX"))
41+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
42+ .toFormatter()
43+ .withZone(ZoneOffset.UTC);
44+
45+ public static OffsetDateTime parseDateTimeString(String str) {
46+ return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();
47+ }
48+
49+ private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
50+ .appendOptional(DateTimeFormatter.ISO_TIME)
51+ .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)
52+ .parseDefaulting(ChronoField.YEAR, 2020)
53+ .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
54+ .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
55+ .toFormatter()
56+ .withZone(ZoneOffset.UTC);
57+
58+ public static OffsetTime parseTimeString(String str) {
59+ return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();
60+ }
61+ // Serialize/deserialize helpers
62+
63+ public static TopLevel fromJsonString(String json) throws IOException {
64+ return getObjectReader().readValue(json);
65+ }
66+
67+ public static String toJsonString(TopLevel obj) throws JsonProcessingException {
68+ return getObjectWriter().writeValueAsString(obj);
69+ }
70+
71+ private static ObjectReader reader;
72+ private static ObjectWriter writer;
73+
74+ private static void instantiateMapper() {
75+ ObjectMapper mapper = new ObjectMapper();
76+ mapper.findAndRegisterModules();
77+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
78+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
79+ SimpleModule module = new SimpleModule();
80+ module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
81+ @Override
82+ public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
83+ String value = jsonParser.getText();
84+ return Converter.parseDateTimeString(value);
85+ }
86+ });
87+ mapper.registerModule(module);
88+ reader = mapper.readerFor(TopLevel.class);
89+ writer = mapper.writerFor(TopLevel.class);
90+ }
91+
92+ private static ObjectReader getObjectReader() {
93+ if (reader == null) instantiateMapper();
94+ return reader;
95+ }
96+
97+ private static ObjectWriter getObjectWriter() {
98+ if (writer == null) instantiateMapper();
99+ return writer;
100+ }
101+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / FooState.java+24 −0
@@ -0,0 +1,24 @@
1+package io.quicktype;
2+
3+import java.io.IOException;
4+import com.fasterxml.jackson.annotation.*;
5+
6+public enum FooState {
7+ XX, YY;
8+
9+ @JsonValue
10+ public String toValue() {
11+ switch (this) {
12+ case XX: return "xx";
13+ case YY: return "yy";
14+ }
15+ return null;
16+ }
17+
18+ @JsonCreator
19+ public static FooState forValue(String value) throws IOException {
20+ if (value.equals("xx")) return XX;
21+ if (value.equals("yy")) return YY;
22+ throw new IOException("Cannot deserialize FooState");
23+ }
24+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / StateInfoWWW.java+18 −0
@@ -0,0 +1,18 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class StateInfoWWW {
6+ private double changeTime;
7+ private WooState state;
8+
9+ @JsonProperty("changeTime")
10+ public double getChangeTime() { return changeTime; }
11+ @JsonProperty("changeTime")
12+ public void setChangeTime(double value) { this.changeTime = value; }
13+
14+ @JsonProperty("state")
15+ public WooState getState() { return state; }
16+ @JsonProperty("state")
17+ public void setState(WooState value) { this.state = value; }
18+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / StateInfoXxx.java+18 −0
@@ -0,0 +1,18 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class StateInfoXxx {
6+ private double changeTime;
7+ private FooState state;
8+
9+ @JsonProperty("changeTime")
10+ public double getChangeTime() { return changeTime; }
11+ @JsonProperty("changeTime")
12+ public void setChangeTime(double value) { this.changeTime = value; }
13+
14+ @JsonProperty("state")
15+ public FooState getState() { return state; }
16+ @JsonProperty("state")
17+ public void setState(FooState value) { this.state = value; }
18+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / TopLevel.java+18 −0
@@ -0,0 +1,18 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class TopLevel {
6+ private StateInfoXxx foo;
7+ private StateInfoWWW woo;
8+
9+ @JsonProperty("foo")
10+ public StateInfoXxx getFoo() { return foo; }
11+ @JsonProperty("foo")
12+ public void setFoo(StateInfoXxx value) { this.foo = value; }
13+
14+ @JsonProperty("woo")
15+ public StateInfoWWW getWoo() { return woo; }
16+ @JsonProperty("woo")
17+ public void setWoo(StateInfoWWW value) { this.woo = value; }
18+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / WooState.java+28 −0
@@ -0,0 +1,28 @@
1+package io.quicktype;
2+
3+import java.io.IOException;
4+import com.fasterxml.jackson.annotation.*;
5+
6+public enum WooState {
7+ ASD, QWE, ZXC, TYU;
8+
9+ @JsonValue
10+ public String toValue() {
11+ switch (this) {
12+ case ASD: return "asd";
13+ case QWE: return "qwe";
14+ case ZXC: return "zxc";
15+ case TYU: return "tyu";
16+ }
17+ return null;
18+ }
19+
20+ @JsonCreator
21+ public static WooState forValue(String value) throws IOException {
22+ if (value.equals("asd")) return ASD;
23+ if (value.equals("qwe")) return QWE;
24+ if (value.equals("zxc")) return ZXC;
25+ if (value.equals("tyu")) return TYU;
26+ throw new IOException("Cannot deserialize WooState");
27+ }
28+}
Aschema-javadefault / src / main / java / io / quicktype / Converter.java+101 −0
@@ -0,0 +1,101 @@
1+// To use this code, add the following Maven dependency to your project:
2+//
3+//
4+// com.fasterxml.jackson.core : jackson-databind : 2.9.0
5+// com.fasterxml.jackson.datatype : jackson-datatype-jsr310 : 2.9.0
6+//
7+// Import this package:
8+//
9+// import io.quicktype.Converter;
10+//
11+// Then you can deserialize a JSON string with
12+//
13+// TopLevel data = Converter.fromJsonString(jsonString);
14+
15+package io.quicktype;
16+
17+import java.io.IOException;
18+import com.fasterxml.jackson.databind.*;
19+import com.fasterxml.jackson.databind.module.SimpleModule;
20+import com.fasterxml.jackson.core.JsonParser;
21+import com.fasterxml.jackson.core.JsonProcessingException;
22+import java.util.*;
23+import java.time.LocalDate;
24+import java.time.OffsetDateTime;
25+import java.time.OffsetTime;
26+import java.time.ZoneOffset;
27+import java.time.ZonedDateTime;
28+import java.time.format.DateTimeFormatter;
29+import java.time.format.DateTimeFormatterBuilder;
30+import java.time.temporal.ChronoField;
31+
32+public class Converter {
33+ // Date-time helpers
34+
35+ private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
36+ .appendOptional(DateTimeFormatter.ISO_DATE_TIME)
37+ .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
38+ .appendOptional(DateTimeFormatter.ISO_INSTANT)
39+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX"))
40+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX"))
41+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
42+ .toFormatter()
43+ .withZone(ZoneOffset.UTC);
44+
45+ public static OffsetDateTime parseDateTimeString(String str) {
46+ return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();
47+ }
48+
49+ private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
50+ .appendOptional(DateTimeFormatter.ISO_TIME)
51+ .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)
52+ .parseDefaulting(ChronoField.YEAR, 2020)
53+ .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
54+ .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
55+ .toFormatter()
56+ .withZone(ZoneOffset.UTC);
57+
58+ public static OffsetTime parseTimeString(String str) {
59+ return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();
60+ }
61+ // Serialize/deserialize helpers
62+
63+ public static TopLevel fromJsonString(String json) throws IOException {
64+ return getObjectReader().readValue(json);
65+ }
66+
67+ public static String toJsonString(TopLevel obj) throws JsonProcessingException {
68+ return getObjectWriter().writeValueAsString(obj);
69+ }
70+
71+ private static ObjectReader reader;
72+ private static ObjectWriter writer;
73+
74+ private static void instantiateMapper() {
75+ ObjectMapper mapper = new ObjectMapper();
76+ mapper.findAndRegisterModules();
77+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
78+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
79+ SimpleModule module = new SimpleModule();
80+ module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
81+ @Override
82+ public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
83+ String value = jsonParser.getText();
84+ return Converter.parseDateTimeString(value);
85+ }
86+ });
87+ mapper.registerModule(module);
88+ reader = mapper.readerFor(TopLevel.class);
89+ writer = mapper.writerFor(TopLevel.class);
90+ }
91+
92+ private static ObjectReader getObjectReader() {
93+ if (reader == null) instantiateMapper();
94+ return reader;
95+ }
96+
97+ private static ObjectWriter getObjectWriter() {
98+ if (writer == null) instantiateMapper();
99+ return writer;
100+ }
101+}
Aschema-javadefault / src / main / java / io / quicktype / FooState.java+24 −0
@@ -0,0 +1,24 @@
1+package io.quicktype;
2+
3+import java.io.IOException;
4+import com.fasterxml.jackson.annotation.*;
5+
6+public enum FooState {
7+ XX, YY;
8+
9+ @JsonValue
10+ public String toValue() {
11+ switch (this) {
12+ case XX: return "xx";
13+ case YY: return "yy";
14+ }
15+ return null;
16+ }
17+
18+ @JsonCreator
19+ public static FooState forValue(String value) throws IOException {
20+ if (value.equals("xx")) return XX;
21+ if (value.equals("yy")) return YY;
22+ throw new IOException("Cannot deserialize FooState");
23+ }
24+}
Aschema-javadefault / src / main / java / io / quicktype / StateInfoWWW.java+18 −0
@@ -0,0 +1,18 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class StateInfoWWW {
6+ private double changeTime;
7+ private WooState state;
8+
9+ @JsonProperty("changeTime")
10+ public double getChangeTime() { return changeTime; }
11+ @JsonProperty("changeTime")
12+ public void setChangeTime(double value) { this.changeTime = value; }
13+
14+ @JsonProperty("state")
15+ public WooState getState() { return state; }
16+ @JsonProperty("state")
17+ public void setState(WooState value) { this.state = value; }
18+}
Aschema-javadefault / src / main / java / io / quicktype / StateInfoXxx.java+18 −0
@@ -0,0 +1,18 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class StateInfoXxx {
6+ private double changeTime;
7+ private FooState state;
8+
9+ @JsonProperty("changeTime")
10+ public double getChangeTime() { return changeTime; }
11+ @JsonProperty("changeTime")
12+ public void setChangeTime(double value) { this.changeTime = value; }
13+
14+ @JsonProperty("state")
15+ public FooState getState() { return state; }
16+ @JsonProperty("state")
17+ public void setState(FooState value) { this.state = value; }
18+}
Aschema-javadefault / src / main / java / io / quicktype / TopLevel.java+18 −0
@@ -0,0 +1,18 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class TopLevel {
6+ private StateInfoXxx foo;
7+ private StateInfoWWW woo;
8+
9+ @JsonProperty("foo")
10+ public StateInfoXxx getFoo() { return foo; }
11+ @JsonProperty("foo")
12+ public void setFoo(StateInfoXxx value) { this.foo = value; }
13+
14+ @JsonProperty("woo")
15+ public StateInfoWWW getWoo() { return woo; }
16+ @JsonProperty("woo")
17+ public void setWoo(StateInfoWWW value) { this.woo = value; }
18+}
Aschema-javadefault / src / main / java / io / quicktype / WooState.java+28 −0
@@ -0,0 +1,28 @@
1+package io.quicktype;
2+
3+import java.io.IOException;
4+import com.fasterxml.jackson.annotation.*;
5+
6+public enum WooState {
7+ ASD, QWE, ZXC, TYU;
8+
9+ @JsonValue
10+ public String toValue() {
11+ switch (this) {
12+ case ASD: return "asd";
13+ case QWE: return "qwe";
14+ case ZXC: return "zxc";
15+ case TYU: return "tyu";
16+ }
17+ return null;
18+ }
19+
20+ @JsonCreator
21+ public static WooState forValue(String value) throws IOException {
22+ if (value.equals("asd")) return ASD;
23+ if (value.equals("qwe")) return QWE;
24+ if (value.equals("zxc")) return ZXC;
25+ if (value.equals("tyu")) return TYU;
26+ throw new IOException("Cannot deserialize WooState");
27+ }
28+}
Aschema-javascriptdefault / TopLevel.js+201 −0
@@ -0,0 +1,201 @@
1+// To parse this data:
2+//
3+// const Convert = require("./TopLevel");
4+//
5+// const topLevel = Convert.toTopLevel(json);
6+//
7+// These functions will throw an error if the JSON doesn't
8+// match the expected interface, even if the JSON is valid.
9+
10+// Converts JSON strings to/from your types
11+// and asserts the results of JSON.parse at runtime
12+function toTopLevel(json) {
13+ return cast(JSON.parse(json), r("TopLevel"));
14+}
15+
16+function topLevelToJson(value) {
17+ return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
18+}
19+
20+function invalidValue(typ, val, key, parent = '') {
21+ const prettyTyp = prettyTypeName(typ);
22+ const parentText = parent ? ` on ${parent}` : '';
23+ const keyText = key ? ` for key "${key}"` : '';
24+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
25+}
26+
27+function prettyTypeName(typ) {
28+ if (Array.isArray(typ)) {
29+ if (typ.length === 2 && typ[0] === undefined) {
30+ return `an optional ${prettyTypeName(typ[1])}`;
31+ } else {
32+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
33+ }
34+ } else if (typeof typ === "object" && typ.literal !== undefined) {
35+ return typ.literal;
36+ } else {
37+ return typeof typ;
38+ }
39+}
40+
41+function jsonToJSProps(typ) {
42+ if (typ.jsonToJS === undefined) {
43+ const map = {};
44+ typ.props.forEach((p) => map[p.json] = { key: p.js, typ: p.typ });
45+ typ.jsonToJS = map;
46+ }
47+ return typ.jsonToJS;
48+}
49+
50+function jsToJSONProps(typ) {
51+ if (typ.jsToJSON === undefined) {
52+ const map = {};
53+ typ.props.forEach((p) => map[p.js] = { key: p.json, typ: p.typ });
54+ typ.jsToJSON = map;
55+ }
56+ return typ.jsToJSON;
57+}
58+
59+function transform(val, typ, getProps, key = '', parent = '') {
60+ function transformPrimitive(typ, val) {
61+ if (typeof typ === typeof val) return val;
62+ return invalidValue(typ, val, key, parent);
63+ }
64+
65+ function transformUnion(typs, val) {
66+ // val must validate against one typ in typs
67+ const l = typs.length;
68+ for (let i = 0; i < l; i++) {
69+ const typ = typs[i];
70+ try {
71+ return transform(val, typ, getProps);
72+ } catch (_) {}
73+ }
74+ return invalidValue(typs, val, key, parent);
75+ }
76+
77+ function transformEnum(cases, val) {
78+ if (cases.indexOf(val) !== -1) return val;
79+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
80+ }
81+
82+ function transformArray(typ, val) {
83+ // val must be an array with no invalid elements
84+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
85+ return val.map(el => transform(el, typ, getProps));
86+ }
87+
88+ function transformDate(val) {
89+ if (val === null) {
90+ return null;
91+ }
92+ const d = new Date(val);
93+ if (isNaN(d.valueOf())) {
94+ return invalidValue(l("Date"), val, key, parent);
95+ }
96+ return d;
97+ }
98+
99+ function transformObject(props, additional, val) {
100+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
101+ return invalidValue(l(ref || "object"), val, key, parent);
102+ }
103+ const result = {};
104+ Object.getOwnPropertyNames(props).forEach(key => {
105+ const prop = props[key];
106+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
107+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
108+ });
109+ Object.getOwnPropertyNames(val).forEach(key => {
110+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
111+ result[key] = transform(val[key], additional, getProps, key, ref);
112+ }
113+ });
114+ return result;
115+ }
116+
117+ if (typ === "any") return val;
118+ if (typ === null) {
119+ if (val === null) return val;
120+ return invalidValue(typ, val, key, parent);
121+ }
122+ if (typ === false) return invalidValue(typ, val, key, parent);
123+ let ref = undefined;
124+ while (typeof typ === "object" && typ.ref !== undefined) {
125+ ref = typ.ref;
126+ typ = typeMap[typ.ref];
127+ }
128+ if (Array.isArray(typ)) return transformEnum(typ, val);
129+ if (typeof typ === "object") {
130+ return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
131+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
132+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
133+ : invalidValue(typ, val, key, parent);
134+ }
135+ // Numbers can be parsed by Date but shouldn't be.
136+ if (typ === Date && typeof val !== "number") return transformDate(val);
137+ return transformPrimitive(typ, val);
138+}
139+
140+function cast(val, typ) {
141+ return transform(val, typ, jsonToJSProps);
142+}
143+
144+function uncast(val, typ) {
145+ return transform(val, typ, jsToJSONProps);
146+}
147+
148+function l(typ) {
149+ return { literal: typ };
150+}
151+
152+function a(typ) {
153+ return { arrayItems: typ };
154+}
155+
156+function u(...typs) {
157+ return { unionMembers: typs };
158+}
159+
160+function o(props, additional) {
161+ return { props, additional };
162+}
163+
164+function m(additional) {
165+ const props = [];
166+ return { props, additional };
167+}
168+
169+function r(name) {
170+ return { ref: name };
171+}
172+
173+const typeMap = {
174+ "TopLevel": o([
175+ { json: "foo", js: "foo", typ: r("StateInfoXxx") },
176+ { json: "woo", js: "woo", typ: r("StateInfoWWW") },
177+ ], false),
178+ "StateInfoXxx": o([
179+ { json: "changeTime", js: "changeTime", typ: 3.14 },
180+ { json: "state", js: "state", typ: r("FooState") },
181+ ], false),
182+ "StateInfoWWW": o([
183+ { json: "changeTime", js: "changeTime", typ: 3.14 },
184+ { json: "state", js: "state", typ: r("WooState") },
185+ ], false),
186+ "FooState": [
187+ "xx",
188+ "yy",
189+ ],
190+ "WooState": [
191+ "asd",
192+ "qwe",
193+ "zxc",
194+ "tyu",
195+ ],
196+};
197+
198+module.exports = {
199+ "topLevelToJson": topLevelToJson,
200+ "toTopLevel": toTopLevel,
201+};
Aschema-kotlin-jacksondefault / TopLevel.kt+92 −0
@@ -0,0 +1,92 @@
1+// To parse the JSON, install jackson-module-kotlin and do:
2+//
3+// val topLevel = TopLevel.fromJson(jsonString)
4+
5+package quicktype
6+
7+import com.fasterxml.jackson.annotation.*
8+import com.fasterxml.jackson.core.*
9+import com.fasterxml.jackson.databind.*
10+import com.fasterxml.jackson.databind.deser.std.StdDeserializer
11+import com.fasterxml.jackson.databind.module.SimpleModule
12+import com.fasterxml.jackson.databind.node.*
13+import com.fasterxml.jackson.databind.ser.std.StdSerializer
14+import com.fasterxml.jackson.module.kotlin.*
15+
16+
17+@Suppress("UNCHECKED_CAST")
18+private fun <T> ObjectMapper.convert(k: kotlin.reflect.KClass<*>, fromJson: (JsonNode) -> T, toJson: (T) -> String, isUnion: Boolean = false) = registerModule(SimpleModule().apply {
19+ addSerializer(k.java as Class<T>, object : StdSerializer<T>(k.java as Class<T>) {
20+ override fun serialize(value: T, gen: JsonGenerator, provider: SerializerProvider) = gen.writeRawValue(toJson(value))
21+ })
22+ addDeserializer(k.java as Class<T>, object : StdDeserializer<T>(k.java as Class<T>) {
23+ override fun deserialize(p: JsonParser, ctxt: DeserializationContext) = fromJson(p.readValueAsTree())
24+ })
25+})
26+
27+val mapper = jacksonObjectMapper().apply {
28+ propertyNamingStrategy = PropertyNamingStrategy.LOWER_CAMEL_CASE
29+ setSerializationInclusion(JsonInclude.Include.NON_NULL)
30+ convert(FooState::class, { FooState.fromValue(it.asText()) }, { "\"${it.value}\"" })
31+ convert(WooState::class, { WooState.fromValue(it.asText()) }, { "\"${it.value}\"" })
32+}
33+
34+data class TopLevel (
35+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
36+ val foo: StateInfoXxx,
37+
38+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
39+ val woo: StateInfoWWW
40+) {
41+ fun toJson() = mapper.writeValueAsString(this)
42+
43+ companion object {
44+ fun fromJson(json: String) = mapper.readValue<TopLevel>(json)
45+ }
46+}
47+
48+data class StateInfoXxx (
49+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
50+ val changeTime: Double,
51+
52+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
53+ val state: FooState
54+)
55+
56+enum class FooState(val value: String) {
57+ Xx("xx"),
58+ Yy("yy");
59+
60+ companion object {
61+ fun fromValue(value: String): FooState = when (value) {
62+ "xx" -> Xx
63+ "yy" -> Yy
64+ else -> throw IllegalArgumentException()
65+ }
66+ }
67+}
68+
69+data class StateInfoWWW (
70+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
71+ val changeTime: Double,
72+
73+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
74+ val state: WooState
75+)
76+
77+enum class WooState(val value: String) {
78+ Asd("asd"),
79+ Qwe("qwe"),
80+ Zxc("zxc"),
81+ Tyu("tyu");
82+
83+ companion object {
84+ fun fromValue(value: String): WooState = when (value) {
85+ "asd" -> Asd
86+ "qwe" -> Qwe
87+ "zxc" -> Zxc
88+ "tyu" -> Tyu
89+ else -> throw IllegalArgumentException()
90+ }
91+ }
92+}
Aschema-kotlindefault / TopLevel.kt+70 −0
@@ -0,0 +1,70 @@
1+// To parse the JSON, install Klaxon and do:
2+//
3+// val topLevel = TopLevel.fromJson(jsonString)
4+
5+package quicktype
6+
7+import com.beust.klaxon.*
8+
9+private fun <T> Klaxon.convert(k: kotlin.reflect.KClass<*>, fromJson: (JsonValue) -> T, toJson: (T) -> String, isUnion: Boolean = false) =
10+ this.converter(object: Converter {
11+ @Suppress("UNCHECKED_CAST")
12+ override fun toJson(value: Any) = toJson(value as T)
13+ override fun fromJson(jv: JsonValue) = fromJson(jv) as Any
14+ override fun canConvert(cls: Class<*>) = cls == k.java || (isUnion && cls.superclass == k.java)
15+ })
16+
17+private val klaxon = Klaxon()
18+ .convert(FooState::class, { FooState.fromValue(it.string!!) }, { "\"${it.value}\"" })
19+ .convert(WooState::class, { WooState.fromValue(it.string!!) }, { "\"${it.value}\"" })
20+
21+data class TopLevel (
22+ val foo: StateInfoXxx,
23+ val woo: StateInfoWWW
24+) {
25+ public fun toJson() = klaxon.toJsonString(this)
26+
27+ companion object {
28+ public fun fromJson(json: String) = klaxon.parse<TopLevel>(json)
29+ }
30+}
31+
32+data class StateInfoXxx (
33+ val changeTime: Double,
34+ val state: FooState
35+)
36+
37+enum class FooState(val value: String) {
38+ Xx("xx"),
39+ Yy("yy");
40+
41+ companion object {
42+ public fun fromValue(value: String): FooState = when (value) {
43+ "xx" -> Xx
44+ "yy" -> Yy
45+ else -> throw IllegalArgumentException()
46+ }
47+ }
48+}
49+
50+data class StateInfoWWW (
51+ val changeTime: Double,
52+ val state: WooState
53+)
54+
55+enum class WooState(val value: String) {
56+ Asd("asd"),
57+ Qwe("qwe"),
58+ Zxc("zxc"),
59+ Tyu("tyu");
60+
61+ companion object {
62+ public fun fromValue(value: String): WooState = when (value) {
63+ "asd" -> Asd
64+ "qwe" -> Qwe
65+ "zxc" -> Zxc
66+ "tyu" -> Tyu
67+ else -> throw IllegalArgumentException()
68+ }
69+ }
70+}
Aschema-kotlinxdefault / TopLevel.kt+43 −0
@@ -0,0 +1,43 @@
1+// To parse the JSON, install kotlin's serialization plugin and do:
2+//
3+// val json = Json { allowStructuredMapKeys = true }
4+// val topLevel = json.parse(TopLevel.serializer(), jsonString)
5+
6+package quicktype
7+
8+import kotlinx.serialization.*
9+import kotlinx.serialization.json.*
10+import kotlinx.serialization.descriptors.*
11+import kotlinx.serialization.encoding.*
12+
13+@Serializable
14+data class TopLevel (
15+ val foo: StateInfoXxx,
16+ val woo: StateInfoWWW
17+)
18+
19+@Serializable
20+data class StateInfoXxx (
21+ val changeTime: Double,
22+ val state: FooState
23+)
24+
25+@Serializable
26+enum class FooState(val value: String) {
27+ @SerialName("xx") Xx("xx"),
28+ @SerialName("yy") Yy("yy");
29+}
30+
31+@Serializable
32+data class StateInfoWWW (
33+ val changeTime: Double,
34+ val state: WooState
35+)
36+
37+@Serializable
38+enum class WooState(val value: String) {
39+ @SerialName("asd") Asd("asd"),
40+ @SerialName("qwe") Qwe("qwe"),
41+ @SerialName("zxc") Zxc("zxc"),
42+ @SerialName("tyu") Tyu("tyu");
43+}
Aschema-phpdefault / TopLevel.php+568 −0
@@ -0,0 +1,568 @@
1+<?php
2+declare(strict_types=1);
3+
4+// This is an autogenerated file:TopLevel
5+
6+class TopLevel {
7+ private StateInfoXxx $foo; // json:foo Required
8+ private StateInfoWWW $woo; // json:woo Required
9+
10+ /**
11+ * @param StateInfoXxx $foo
12+ * @param StateInfoWWW $woo
13+ */
14+ public function __construct(StateInfoXxx $foo, StateInfoWWW $woo) {
15+ $this->foo = $foo;
16+ $this->woo = $woo;
17+ }
18+
19+ /**
20+ * @param stdClass $value
21+ * @throws Exception
22+ * @return StateInfoXxx
23+ */
24+ public static function fromFoo(stdClass $value): StateInfoXxx {
25+ return StateInfoXxx::from($value); /*class*/
26+ }
27+
28+ /**
29+ * @throws Exception
30+ * @return stdClass
31+ */
32+ public function toFoo(): stdClass {
33+ if (TopLevel::validateFoo($this->foo)) {
34+ return $this->foo->to(); /*class*/
35+ }
36+ throw new Exception('never get to this TopLevel::foo');
37+ }
38+
39+ /**
40+ * @param StateInfoXxx
41+ * @return bool
42+ * @throws Exception
43+ */
44+ public static function validateFoo(StateInfoXxx $value): bool {
45+ $value->validate();
46+ return true;
47+ }
48+
49+ /**
50+ * @throws Exception
51+ * @return StateInfoXxx
52+ */
53+ public function getFoo(): StateInfoXxx {
54+ if (TopLevel::validateFoo($this->foo)) {
55+ return $this->foo;
56+ }
57+ throw new Exception('never get to getFoo TopLevel::foo');
58+ }
59+
60+ /**
61+ * @return StateInfoXxx
62+ */
63+ public static function sampleFoo(): StateInfoXxx {
64+ return StateInfoXxx::sample(); /*31:foo*/
65+ }
66+
67+ /**
68+ * @param stdClass $value
69+ * @throws Exception
70+ * @return StateInfoWWW
71+ */
72+ public static function fromWoo(stdClass $value): StateInfoWWW {
73+ return StateInfoWWW::from($value); /*class*/
74+ }
75+
76+ /**
77+ * @throws Exception
78+ * @return stdClass
79+ */
80+ public function toWoo(): stdClass {
81+ if (TopLevel::validateWoo($this->woo)) {
82+ return $this->woo->to(); /*class*/
83+ }
84+ throw new Exception('never get to this TopLevel::woo');
85+ }
86+
87+ /**
88+ * @param StateInfoWWW
89+ * @return bool
90+ * @throws Exception
91+ */
92+ public static function validateWoo(StateInfoWWW $value): bool {
93+ $value->validate();
94+ return true;
95+ }
96+
97+ /**
98+ * @throws Exception
99+ * @return StateInfoWWW
100+ */
101+ public function getWoo(): StateInfoWWW {
102+ if (TopLevel::validateWoo($this->woo)) {
103+ return $this->woo;
104+ }
105+ throw new Exception('never get to getWoo TopLevel::woo');
106+ }
107+
108+ /**
109+ * @return StateInfoWWW
110+ */
111+ public static function sampleWoo(): StateInfoWWW {
112+ return StateInfoWWW::sample(); /*32:woo*/
113+ }
114+
115+ /**
116+ * @throws Exception
117+ * @return bool
118+ */
119+ public function validate(): bool {
120+ return TopLevel::validateFoo($this->foo)
121+ || TopLevel::validateWoo($this->woo);
122+ }
123+
124+ /**
125+ * @return stdClass
126+ * @throws Exception
127+ */
128+ public function to(): stdClass {
129+ $out = new stdClass();
130+ $out->{'foo'} = $this->toFoo();
131+ $out->{'woo'} = $this->toWoo();
132+ return $out;
133+ }
134+
135+ /**
136+ * @param stdClass $obj
137+ * @return TopLevel
138+ * @throws Exception
139+ */
140+ public static function from(stdClass $obj): TopLevel {
141+ return new TopLevel(
142+ TopLevel::fromFoo($obj->{'foo'})
143+ ,TopLevel::fromWoo($obj->{'woo'})
144+ );
145+ }
146+
147+ /**
148+ * @return TopLevel
149+ */
150+ public static function sample(): TopLevel {
151+ return new TopLevel(
152+ TopLevel::sampleFoo()
153+ ,TopLevel::sampleWoo()
154+ );
155+ }
156+}
157+
158+// This is an autogenerated file:StateInfoXxx
159+
160+class StateInfoXxx {
161+ private float $changeTime; // json:changeTime Required
162+ private FooState $state; // json:state Required
163+
164+ /**
165+ * @param float $changeTime
166+ * @param FooState $state
167+ */
168+ public function __construct(float $changeTime, FooState $state) {
169+ $this->changeTime = $changeTime;
170+ $this->state = $state;
171+ }
172+
173+ /**
174+ * @param float $value
175+ * @throws Exception
176+ * @return float
177+ */
178+ public static function fromChangeTime(float $value): float {
179+ return $value; /*float*/
180+ }
181+
182+ /**
183+ * @throws Exception
184+ * @return float
185+ */
186+ public function toChangeTime(): float {
187+ if (StateInfoXxx::validateChangeTime($this->changeTime)) {
188+ return $this->changeTime; /*float*/
189+ }
190+ throw new Exception('never get to this StateInfoXxx::changeTime');
191+ }
192+
193+ /**
194+ * @param float
195+ * @return bool
196+ * @throws Exception
197+ */
198+ public static function validateChangeTime(float $value): bool {
199+ return true;
200+ }
201+
202+ /**
203+ * @throws Exception
204+ * @return float
205+ */
206+ public function getChangeTime(): float {
207+ if (StateInfoXxx::validateChangeTime($this->changeTime)) {
208+ return $this->changeTime;
209+ }
210+ throw new Exception('never get to getChangeTime StateInfoXxx::changeTime');
211+ }
212+
213+ /**
214+ * @return float
215+ */
216+ public static function sampleChangeTime(): float {
217+ return 31.031; /*31:changeTime*/
218+ }
219+
220+ /**
221+ * @param string $value
222+ * @throws Exception
223+ * @return FooState
224+ */
225+ public static function fromState(string $value): FooState {
226+ return FooState::from($value); /*enum*/
227+ }
228+
229+ /**
230+ * @throws Exception
231+ * @return string
232+ */
233+ public function toState(): string {
234+ if (StateInfoXxx::validateState($this->state)) {
235+ return FooState::to($this->state); /*enum*/
236+ }
237+ throw new Exception('never get to this StateInfoXxx::state');
238+ }
239+
240+ /**
241+ * @param FooState
242+ * @return bool
243+ * @throws Exception
244+ */
245+ public static function validateState(FooState $value): bool {
246+ FooState::to($value);
247+ return true;
248+ }
249+
250+ /**
251+ * @throws Exception
252+ * @return FooState
253+ */
254+ public function getState(): FooState {
255+ if (StateInfoXxx::validateState($this->state)) {
256+ return $this->state;
257+ }
258+ throw new Exception('never get to getState StateInfoXxx::state');
259+ }
260+
261+ /**
262+ * @return FooState
263+ */
264+ public static function sampleState(): FooState {
265+ return FooState::sample(); /*enum*/
266+ }
267+
268+ /**
269+ * @throws Exception
270+ * @return bool
271+ */
272+ public function validate(): bool {
273+ return StateInfoXxx::validateChangeTime($this->changeTime)
274+ || StateInfoXxx::validateState($this->state);
275+ }
276+
277+ /**
278+ * @return stdClass
279+ * @throws Exception
280+ */
281+ public function to(): stdClass {
282+ $out = new stdClass();
283+ $out->{'changeTime'} = $this->toChangeTime();
284+ $out->{'state'} = $this->toState();
285+ return $out;
286+ }
287+
288+ /**
289+ * @param stdClass $obj
290+ * @return StateInfoXxx
291+ * @throws Exception
292+ */
293+ public static function from(stdClass $obj): StateInfoXxx {
294+ return new StateInfoXxx(
295+ StateInfoXxx::fromChangeTime($obj->{'changeTime'})
296+ ,StateInfoXxx::fromState($obj->{'state'})
297+ );
298+ }
299+
300+ /**
301+ * @return StateInfoXxx
302+ */
303+ public static function sample(): StateInfoXxx {
304+ return new StateInfoXxx(
305+ StateInfoXxx::sampleChangeTime()
306+ ,StateInfoXxx::sampleState()
307+ );
308+ }
309+}
310+
311+// This is an autogenerated file:FooState
312+
313+class FooState {
314+ public static FooState $XX;
315+ public static FooState $YY;
316+ public static function init() {
317+ FooState::$XX = new FooState('xx');
318+ FooState::$YY = new FooState('yy');
319+ }
320+ private string $enum;
321+ public function __construct(string $enum) {
322+ $this->enum = $enum;
323+ }
324+
325+ /**
326+ * @param FooState
327+ * @return string
328+ * @throws Exception
329+ */
330+ public static function to(FooState $obj): string {
331+ switch ($obj->enum) {
332+ case FooState::$XX->enum: return 'xx';
333+ case FooState::$YY->enum: return 'yy';
334+ }
335+ throw new Exception('the give value is not an enum-value.');
336+ }
337+
338+ /**
339+ * @param mixed
340+ * @return FooState
341+ * @throws Exception
342+ */
343+ public static function from($obj): FooState {
344+ switch ($obj) {
345+ case 'xx': return FooState::$XX;
346+ case 'yy': return FooState::$YY;
347+ }
348+ throw new Exception("Cannot deserialize FooState");
349+ }
350+
351+ /**
352+ * @return FooState
353+ */
354+ public static function sample(): FooState {
355+ return FooState::$XX;
356+ }
357+}
358+FooState::init();
359+
360+// This is an autogenerated file:StateInfoWWW
361+
362+class StateInfoWWW {
363+ private float $changeTime; // json:changeTime Required
364+ private WooState $state; // json:state Required
365+
366+ /**
367+ * @param float $changeTime
368+ * @param WooState $state
369+ */
370+ public function __construct(float $changeTime, WooState $state) {
371+ $this->changeTime = $changeTime;
372+ $this->state = $state;
373+ }
374+
375+ /**
376+ * @param float $value
377+ * @throws Exception
378+ * @return float
379+ */
380+ public static function fromChangeTime(float $value): float {
381+ return $value; /*float*/
382+ }
383+
384+ /**
385+ * @throws Exception
386+ * @return float
387+ */
388+ public function toChangeTime(): float {
389+ if (StateInfoWWW::validateChangeTime($this->changeTime)) {
390+ return $this->changeTime; /*float*/
391+ }
392+ throw new Exception('never get to this StateInfoWWW::changeTime');
393+ }
394+
395+ /**
396+ * @param float
397+ * @return bool
398+ * @throws Exception
399+ */
400+ public static function validateChangeTime(float $value): bool {
401+ return true;
402+ }
403+
404+ /**
405+ * @throws Exception
406+ * @return float
407+ */
408+ public function getChangeTime(): float {
409+ if (StateInfoWWW::validateChangeTime($this->changeTime)) {
410+ return $this->changeTime;
411+ }
412+ throw new Exception('never get to getChangeTime StateInfoWWW::changeTime');
413+ }
414+
415+ /**
416+ * @return float
417+ */
418+ public static function sampleChangeTime(): float {
419+ return 31.031; /*31:changeTime*/
420+ }
421+
422+ /**
423+ * @param string $value
424+ * @throws Exception
425+ * @return WooState
426+ */
427+ public static function fromState(string $value): WooState {
428+ return WooState::from($value); /*enum*/
429+ }
430+
431+ /**
432+ * @throws Exception
433+ * @return string
434+ */
435+ public function toState(): string {
436+ if (StateInfoWWW::validateState($this->state)) {
437+ return WooState::to($this->state); /*enum*/
438+ }
439+ throw new Exception('never get to this StateInfoWWW::state');
440+ }
441+
442+ /**
443+ * @param WooState
444+ * @return bool
445+ * @throws Exception
446+ */
447+ public static function validateState(WooState $value): bool {
448+ WooState::to($value);
449+ return true;
450+ }
451+
452+ /**
453+ * @throws Exception
454+ * @return WooState
455+ */
456+ public function getState(): WooState {
457+ if (StateInfoWWW::validateState($this->state)) {
458+ return $this->state;
459+ }
460+ throw new Exception('never get to getState StateInfoWWW::state');
461+ }
462+
463+ /**
464+ * @return WooState
465+ */
466+ public static function sampleState(): WooState {
467+ return WooState::sample(); /*enum*/
468+ }
469+
470+ /**
471+ * @throws Exception
472+ * @return bool
473+ */
474+ public function validate(): bool {
475+ return StateInfoWWW::validateChangeTime($this->changeTime)
476+ || StateInfoWWW::validateState($this->state);
477+ }
478+
479+ /**
480+ * @return stdClass
481+ * @throws Exception
482+ */
483+ public function to(): stdClass {
484+ $out = new stdClass();
485+ $out->{'changeTime'} = $this->toChangeTime();
486+ $out->{'state'} = $this->toState();
487+ return $out;
488+ }
489+
490+ /**
491+ * @param stdClass $obj
492+ * @return StateInfoWWW
493+ * @throws Exception
494+ */
495+ public static function from(stdClass $obj): StateInfoWWW {
496+ return new StateInfoWWW(
497+ StateInfoWWW::fromChangeTime($obj->{'changeTime'})
498+ ,StateInfoWWW::fromState($obj->{'state'})
499+ );
500+ }
501+
502+ /**
503+ * @return StateInfoWWW
504+ */
505+ public static function sample(): StateInfoWWW {
506+ return new StateInfoWWW(
507+ StateInfoWWW::sampleChangeTime()
508+ ,StateInfoWWW::sampleState()
509+ );
510+ }
511+}
512+
513+// This is an autogenerated file:WooState
514+
515+class WooState {
516+ public static WooState $ASD;
517+ public static WooState $QWE;
518+ public static WooState $ZXC;
519+ public static WooState $TYU;
520+ public static function init() {
521+ WooState::$ASD = new WooState('asd');
522+ WooState::$QWE = new WooState('qwe');
523+ WooState::$ZXC = new WooState('zxc');
524+ WooState::$TYU = new WooState('tyu');
525+ }
526+ private string $enum;
527+ public function __construct(string $enum) {
528+ $this->enum = $enum;
529+ }
530+
531+ /**
532+ * @param WooState
533+ * @return string
534+ * @throws Exception
535+ */
536+ public static function to(WooState $obj): string {
537+ switch ($obj->enum) {
538+ case WooState::$ASD->enum: return 'asd';
539+ case WooState::$QWE->enum: return 'qwe';
540+ case WooState::$ZXC->enum: return 'zxc';
541+ case WooState::$TYU->enum: return 'tyu';
542+ }
543+ throw new Exception('the give value is not an enum-value.');
544+ }
545+
546+ /**
547+ * @param mixed
548+ * @return WooState
549+ * @throws Exception
550+ */
551+ public static function from($obj): WooState {
552+ switch ($obj) {
553+ case 'asd': return WooState::$ASD;
554+ case 'qwe': return WooState::$QWE;
555+ case 'zxc': return WooState::$ZXC;
556+ case 'tyu': return WooState::$TYU;
557+ }
558+ throw new Exception("Cannot deserialize WooState");
559+ }
560+
561+ /**
562+ * @return WooState
563+ */
564+ public static function sample(): WooState {
565+ return WooState::$ASD;
566+ }
567+}
568+WooState::init();
Aschema-pikedefault / TopLevel.pmod+94 −0
@@ -0,0 +1,94 @@
1+// This source has been automatically generated by quicktype.
2+// ( https://github.com/quicktype/quicktype )
3+//
4+// To use this code, simply import it into your project as a Pike module.
5+// To JSON-encode your object, you can pass it to `Standards.JSON.encode`
6+// or call `encode_json` on it.
7+//
8+// To decode a JSON string, first pass it to `Standards.JSON.decode`,
9+// and then pass the result to `<YourClass>_from_JSON`.
10+// It will return an instance of <YourClass>.
11+// Bear in mind that these functions have unexpected behavior,
12+// and will likely throw an error, if the JSON string does not
13+// match the expected interface, even if the JSON itself is valid.
14+
15+class TopLevel {
16+ StateInfoXxx foo; // json: "foo"
17+ StateInfoWww woo; // json: "woo"
18+
19+ string encode_json() {
20+ mapping(string:mixed) json = ([
21+ "foo" : foo,
22+ "woo" : woo,
23+ ]);
24+
25+ return Standards.JSON.encode(json);
26+ }
27+}
28+
29+TopLevel TopLevel_from_JSON(mixed json) {
30+ TopLevel retval = TopLevel();
31+
32+ retval.foo = json["foo"];
33+ retval.woo = json["woo"];
34+
35+ return retval;
36+}
37+
38+class StateInfoXxx {
39+ float change_time; // json: "changeTime"
40+ FooState state; // json: "state"
41+
42+ string encode_json() {
43+ mapping(string:mixed) json = ([
44+ "changeTime" : change_time,
45+ "state" : state,
46+ ]);
47+
48+ return Standards.JSON.encode(json);
49+ }
50+}
51+
52+StateInfoXxx StateInfoXxx_from_JSON(mixed json) {
53+ StateInfoXxx retval = StateInfoXxx();
54+
55+ retval.change_time = json["changeTime"];
56+ retval.state = json["state"];
57+
58+ return retval;
59+}
60+
61+enum FooState {
62+ XX = "xx", // json: "xx"
63+ YY = "yy", // json: "yy"
64+}
65+
66+class StateInfoWww {
67+ float change_time; // json: "changeTime"
68+ WooState state; // json: "state"
69+
70+ string encode_json() {
71+ mapping(string:mixed) json = ([
72+ "changeTime" : change_time,
73+ "state" : state,
74+ ]);
75+
76+ return Standards.JSON.encode(json);
77+ }
78+}
79+
80+StateInfoWww StateInfoWww_from_JSON(mixed json) {
81+ StateInfoWww retval = StateInfoWww();
82+
83+ retval.change_time = json["changeTime"];
84+ retval.state = json["state"];
85+
86+ return retval;
87+}
88+
89+enum WooState {
90+ ASD = "asd", // json: "asd"
91+ QWE = "qwe", // json: "qwe"
92+ ZXC = "zxc", // json: "zxc"
93+ TYU = "tyu", // json: "tyu"
94+}
Aschema-pythondefault / quicktype.py+104 −0
@@ -0,0 +1,104 @@
1+from enum import Enum
2+from dataclasses import dataclass
3+from typing import Any, TypeVar, Type, cast
4+
5+
6+T = TypeVar("T")
7+EnumT = TypeVar("EnumT", bound=Enum)
8+
9+
10+def from_float(x: Any) -> float:
11+ assert isinstance(x, (float, int)) and not isinstance(x, bool)
12+ return float(x)
13+
14+
15+def to_float(x: Any) -> float:
16+ assert isinstance(x, (int, float))
17+ return x
18+
19+
20+def to_enum(c: Type[EnumT], x: Any) -> EnumT:
21+ assert isinstance(x, c)
22+ return x.value
23+
24+
25+def to_class(c: Type[T], x: Any) -> dict:
26+ assert isinstance(x, c)
27+ return cast(Any, x).to_dict()
28+
29+
30+class FooState(Enum):
31+ XX = "xx"
32+ YY = "yy"
33+
34+
35+@dataclass
36+class StateInfoXxx:
37+ change_time: float
38+ state: FooState
39+
40+ @staticmethod
41+ def from_dict(obj: Any) -> 'StateInfoXxx':
42+ assert isinstance(obj, dict)
43+ change_time = from_float(obj.get("changeTime"))
44+ state = FooState(obj.get("state"))
45+ return StateInfoXxx(change_time, state)
46+
47+ def to_dict(self) -> dict:
48+ result: dict = {}
49+ result["changeTime"] = to_float(self.change_time)
50+ result["state"] = to_enum(FooState, self.state)
51+ return result
52+
53+
54+class WooState(Enum):
55+ ASD = "asd"
56+ QWE = "qwe"
57+ ZXC = "zxc"
58+ TYU = "tyu"
59+
60+
61+@dataclass
62+class StateInfoWWW:
63+ change_time: float
64+ state: WooState
65+
66+ @staticmethod
67+ def from_dict(obj: Any) -> 'StateInfoWWW':
68+ assert isinstance(obj, dict)
69+ change_time = from_float(obj.get("changeTime"))
70+ state = WooState(obj.get("state"))
71+ return StateInfoWWW(change_time, state)
72+
73+ def to_dict(self) -> dict:
74+ result: dict = {}
75+ result["changeTime"] = to_float(self.change_time)
76+ result["state"] = to_enum(WooState, self.state)
77+ return result
78+
79+
80+@dataclass
81+class TopLevel:
82+ foo: StateInfoXxx
83+ woo: StateInfoWWW
84+
85+ @staticmethod
86+ def from_dict(obj: Any) -> 'TopLevel':
87+ assert isinstance(obj, dict)
88+ foo = StateInfoXxx.from_dict(obj.get("foo"))
89+ woo = StateInfoWWW.from_dict(obj.get("woo"))
90+ return TopLevel(foo, woo)
91+
92+ def to_dict(self) -> dict:
93+ result: dict = {}
94+ result["foo"] = to_class(StateInfoXxx, self.foo)
95+ result["woo"] = to_class(StateInfoWWW, self.woo)
96+ return result
97+
98+
99+def top_level_from_dict(s: Any) -> TopLevel:
100+ return TopLevel.from_dict(s)
101+
102+
103+def top_level_to_dict(x: TopLevel) -> Any:
104+ return to_class(TopLevel, x)
Aschema-rubydefault / TopLevel.rb+119 −0
@@ -0,0 +1,119 @@
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.woo.change_time
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+ FooState = Strict::String.enum("xx", "yy")
22+ WooState = Strict::String.enum("asd", "qwe", "zxc", "tyu")
23+end
24+
25+module FooState
26+ Xx = "xx"
27+ Yy = "yy"
28+end
29+
30+class StateInfoXxx < Dry::Struct
31+ attribute :change_time, Types::Double
32+ attribute :state, Types::FooState
33+
34+ def self.from_dynamic!(d)
35+ d = Types::Hash[d]
36+ new(
37+ change_time: d.fetch("changeTime"),
38+ state: d.fetch("state"),
39+ )
40+ end
41+
42+ def self.from_json!(json)
43+ from_dynamic!(JSON.parse(json))
44+ end
45+
46+ def to_dynamic
47+ {
48+ "changeTime" => change_time,
49+ "state" => state,
50+ }
51+ end
52+
53+ def to_json(options = nil)
54+ JSON.generate(to_dynamic, options)
55+ end
56+end
57+
58+module WooState
59+ Asd = "asd"
60+ Qwe = "qwe"
61+ Zxc = "zxc"
62+ Tyu = "tyu"
63+end
64+
65+class StateInfoWWW < Dry::Struct
66+ attribute :change_time, Types::Double
67+ attribute :state, Types::WooState
68+
69+ def self.from_dynamic!(d)
70+ d = Types::Hash[d]
71+ new(
72+ change_time: d.fetch("changeTime"),
73+ state: d.fetch("state"),
74+ )
75+ end
76+
77+ def self.from_json!(json)
78+ from_dynamic!(JSON.parse(json))
79+ end
80+
81+ def to_dynamic
82+ {
83+ "changeTime" => change_time,
84+ "state" => state,
85+ }
86+ end
87+
88+ def to_json(options = nil)
89+ JSON.generate(to_dynamic, options)
90+ end
91+end
92+
93+class TopLevel < Dry::Struct
94+ attribute :foo, StateInfoXxx
95+ attribute :woo, StateInfoWWW
96+
97+ def self.from_dynamic!(d)
98+ d = Types::Hash[d]
99+ new(
100+ foo: StateInfoXxx.from_dynamic!(d.fetch("foo")),
101+ woo: StateInfoWWW.from_dynamic!(d.fetch("woo")),
102+ )
103+ end
104+
105+ def self.from_json!(json)
106+ from_dynamic!(JSON.parse(json))
107+ end
108+
109+ def to_dynamic
110+ {
111+ "foo" => foo.to_dynamic,
112+ "woo" => woo.to_dynamic,
113+ }
114+ end
115+
116+ def to_json(options = nil)
117+ JSON.generate(to_dynamic, options)
118+ end
119+end
Aschema-rustdefault / module_under_test.rs+57 −0
@@ -0,0 +1,57 @@
1+// Example code that deserializes and serializes the model.
2+// extern crate serde;
3+// #[macro_use]
4+// extern crate serde_derive;
5+// extern crate serde_json;
6+//
7+// use generated_module::TopLevel;
8+//
9+// fn main() {
10+// let json = r#"{"answer": 42}"#;
11+// let model: TopLevel = serde_json::from_str(&json).unwrap();
12+// }
13+
14+use serde::{Serialize, Deserialize};
15+
16+#[derive(Debug, Clone, Serialize, Deserialize)]
17+pub struct TopLevel {
18+ pub foo: StateInfoXxx,
19+
20+ pub woo: StateInfoWww,
21+}
22+
23+#[derive(Debug, Clone, Serialize, Deserialize)]
24+#[serde(rename_all = "camelCase")]
25+pub struct StateInfoXxx {
26+ pub change_time: f64,
27+
28+ pub state: FooState,
29+}
30+
31+#[derive(Debug, Clone, Serialize, Deserialize)]
32+#[serde(rename_all = "snake_case")]
33+pub enum FooState {
34+ Xx,
35+
36+ Yy,
37+}
38+
39+#[derive(Debug, Clone, Serialize, Deserialize)]
40+#[serde(rename_all = "camelCase")]
41+pub struct StateInfoWww {
42+ pub change_time: f64,
43+
44+ pub state: WooState,
45+}
46+
47+#[derive(Debug, Clone, Serialize, Deserialize)]
48+#[serde(rename_all = "snake_case")]
49+pub enum WooState {
50+ Asd,
51+
52+ Qwe,
53+
54+ Zxc,
55+
56+ Tyu,
57+}
Aschema-scala3-upickledefault / TopLevel.scala+119 −0
@@ -0,0 +1,119 @@
1+package quicktype
2+
3+// Custom pickler so that missing keys and JSON nulls both read as None,
4+// and None is left out when writing (upickle's default for Option is a
5+// JSON array).
6+object OptionPickler extends upickle.AttributeTagged:
7+ import upickle.default.Writer
8+ import upickle.default.Reader
9+ override implicit def OptionWriter[T: Writer]: Writer[Option[T]] =
10+ implicitly[Writer[T]].comap[Option[T]] {
11+ case None => null.asInstanceOf[T]
12+ case Some(x) => x
13+ }
14+
15+ override implicit def OptionReader[T: Reader]: Reader[Option[T]] = {
16+ new Reader.Delegate[Any, Option[T]](implicitly[Reader[T]].map(Some(_))){
17+ override def visitNull(index: Int) = None
18+ }
19+ }
20+end OptionPickler
21+
22+// If a union has a null in, then we'll need this too...
23+type NullValue = None.type
24+given OptionPickler.ReadWriter[NullValue] = OptionPickler.readwriter[ujson.Value].bimap[NullValue](
25+ _ => ujson.Null,
26+ json => if json.isNull then None else throw new upickle.core.Abort("not null")
27+)
28+
29+object JsonExt:
30+ val valueReader = OptionPickler.readwriter[ujson.Value]
31+
32+ // upickle's built-in primitive readers are lenient -- the numeric and
33+ // boolean readers accept strings, and the string reader accepts
34+ // numbers and booleans -- so untagged unions need strict readers to
35+ // pick the right member.
36+ val strictString: OptionPickler.Reader[String] = valueReader.map {
37+ case ujson.Str(s) => s
38+ case json => throw new upickle.core.Abort("expected string, got " + json)
39+ }
40+ val strictLong: OptionPickler.Reader[Long] = valueReader.map {
41+ case ujson.Num(n) if n.isWhole => n.toLong
42+ case json => throw new upickle.core.Abort("expected integer, got " + json)
43+ }
44+ val strictDouble: OptionPickler.Reader[Double] = valueReader.map {
45+ case ujson.Num(n) => n
46+ case json => throw new upickle.core.Abort("expected number, got " + json)
47+ }
48+ val strictBoolean: OptionPickler.Reader[Boolean] = valueReader.map {
49+ case ujson.Bool(b) => b
50+ case json => throw new upickle.core.Abort("expected boolean, got " + json)
51+ }
52+
53+ def badMerge[T](r1: => OptionPickler.Reader[?], rest: OptionPickler.Reader[?]*): OptionPickler.Reader[T] = valueReader.map { json =>
54+ var t: T | Null = null
55+ val stack = Vector.newBuilder[Throwable]
56+ (r1 +: rest).foreach { reader =>
57+ if t == null then
58+ try
59+ t = OptionPickler.read[T](json, trace = true)(using reader.asInstanceOf[OptionPickler.Reader[T]])
60+ catch
61+ case exc => stack += exc
62+ }
63+ if t != null then t.nn else throw new Exception(json.toString(), stack.result().headOption.getOrElse(null))
64+ }
65+end JsonExt
66+
67+
68+case class TopLevel (
69+ val foo : StateInfoXxx,
70+ val woo : StateInfoWWW
71+) derives OptionPickler.ReadWriter
72+
73+case class StateInfoXxx (
74+ val changeTime : Double,
75+ val state : FooState
76+) derives OptionPickler.ReadWriter
77+
78+enum FooState :
79+ case Xx
80+ case Yy
81+
82+given OptionPickler.ReadWriter[FooState] = OptionPickler.readwriter[String].bimap[FooState](
83+ {
84+ case FooState.Xx => "xx"
85+ case FooState.Yy => "yy"
86+ },
87+ {
88+ case "xx" => FooState.Xx
89+ case "yy" => FooState.Yy
90+ case other => throw new upickle.core.Abort("invalid FooState: " + other)
91+ }
92+)
93+
94+case class StateInfoWWW (
95+ val changeTime : Double,
96+ val state : WooState
97+) derives OptionPickler.ReadWriter
98+
99+enum WooState :
100+ case Asd
101+ case Qwe
102+ case Zxc
103+ case Tyu
104+
105+given OptionPickler.ReadWriter[WooState] = OptionPickler.readwriter[String].bimap[WooState](
106+ {
107+ case WooState.Asd => "asd"
108+ case WooState.Qwe => "qwe"
109+ case WooState.Zxc => "zxc"
110+ case WooState.Tyu => "tyu"
111+ },
112+ {
113+ case "asd" => WooState.Asd
114+ case "qwe" => WooState.Qwe
115+ case "zxc" => WooState.Zxc
116+ case "tyu" => WooState.Tyu
117+ case other => throw new upickle.core.Abort("invalid WooState: " + other)
118+ }
119+)
Aschema-scala3default / TopLevel.scala+57 −0
@@ -0,0 +1,57 @@
1+package quicktype
2+
3+import io.circe.syntax._
4+import io.circe._
5+import cats.syntax.functor._
6+
7+// If a union has a null in, then we'll need this too...
8+type NullValue = None.type
9+
10+case class TopLevel (
11+ val foo : StateInfoXxx,
12+ val woo : StateInfoWWW
13+) derives Encoder.AsObject, Decoder
14+
15+case class StateInfoXxx (
16+ val changeTime : Double,
17+ val state : FooState
18+) derives Encoder.AsObject, Decoder
19+
20+enum FooState :
21+ case Xx
22+ case Yy
23+
24+given Decoder[FooState] = Decoder.decodeString.emap {
25+ case "xx" => scala.Right(FooState.Xx)
26+ case "yy" => scala.Right(FooState.Yy)
27+ case other => scala.Left("invalid FooState: " + other)
28+}
29+given Encoder[FooState] = Encoder.encodeString.contramap {
30+ case FooState.Xx => "xx"
31+ case FooState.Yy => "yy"
32+}
33+
34+case class StateInfoWWW (
35+ val changeTime : Double,
36+ val state : WooState
37+) derives Encoder.AsObject, Decoder
38+
39+enum WooState :
40+ case Asd
41+ case Qwe
42+ case Zxc
43+ case Tyu
44+
45+given Decoder[WooState] = Decoder.decodeString.emap {
46+ case "asd" => scala.Right(WooState.Asd)
47+ case "qwe" => scala.Right(WooState.Qwe)
48+ case "zxc" => scala.Right(WooState.Zxc)
49+ case "tyu" => scala.Right(WooState.Tyu)
50+ case other => scala.Left("invalid WooState: " + other)
51+}
52+given Encoder[WooState] = Encoder.encodeString.contramap {
53+ case WooState.Asd => "asd"
54+ case WooState.Qwe => "qwe"
55+ case WooState.Zxc => "zxc"
56+ case WooState.Tyu => "tyu"
57+}
Aschema-schemadefault / TopLevel.schema+75 −0
@@ -0,0 +1,75 @@
1+{
2+ "$schema": "http://json-schema.org/draft-06/schema#",
3+ "$ref": "#/definitions/TopLevel",
4+ "definitions": {
5+ "TopLevel": {
6+ "type": "object",
7+ "additionalProperties": false,
8+ "properties": {
9+ "foo": {
10+ "$ref": "#/definitions/StateInfoXxx"
11+ },
12+ "woo": {
13+ "$ref": "#/definitions/StateInfoWWW"
14+ }
15+ },
16+ "required": [
17+ "foo",
18+ "woo"
19+ ],
20+ "title": "TopLevel"
21+ },
22+ "StateInfoXxx": {
23+ "type": "object",
24+ "additionalProperties": false,
25+ "properties": {
26+ "changeTime": {
27+ "type": "number"
28+ },
29+ "state": {
30+ "$ref": "#/definitions/FooState"
31+ }
32+ },
33+ "required": [
34+ "changeTime",
35+ "state"
36+ ],
37+ "title": "StateInfoXxx"
38+ },
39+ "StateInfoWWW": {
40+ "type": "object",
41+ "additionalProperties": false,
42+ "properties": {
43+ "changeTime": {
44+ "type": "number"
45+ },
46+ "state": {
47+ "$ref": "#/definitions/WooState"
48+ }
49+ },
50+ "required": [
51+ "changeTime",
52+ "state"
53+ ],
54+ "title": "StateInfoWWW"
55+ },
56+ "FooState": {
57+ "type": "string",
58+ "enum": [
59+ "xx",
60+ "yy"
61+ ],
62+ "title": "FooState"
63+ },
64+ "WooState": {
65+ "type": "string",
66+ "enum": [
67+ "asd",
68+ "qwe",
69+ "zxc",
70+ "tyu"
71+ ],
72+ "title": "WooState"
73+ }
74+ }
75+}
Aschema-typescriptdefault / TopLevel.ts+217 −0
@@ -0,0 +1,217 @@
1+// To parse this data:
2+//
3+// import { Convert, TopLevel } from "./TopLevel";
4+//
5+// const topLevel = Convert.toTopLevel(json);
6+//
7+// These functions will throw an error if the JSON doesn't
8+// match the expected interface, even if the JSON is valid.
9+
10+export interface TopLevel {
11+ foo: StateInfoXxx;
12+ woo: StateInfoWWW;
13+}
14+
15+export interface StateInfoXxx {
16+ changeTime: number;
17+ state: FooState;
18+}
19+
20+export type FooState = "xx" | "yy";
21+
22+export interface StateInfoWWW {
23+ changeTime: number;
24+ state: WooState;
25+}
26+
27+export type WooState = "asd" | "qwe" | "zxc" | "tyu";
28+
29+// Converts JSON strings to/from your types
30+// and asserts the results of JSON.parse at runtime
31+export class Convert {
32+ public static toTopLevel(json: string): TopLevel {
33+ return cast(JSON.parse(json), r("TopLevel"));
34+ }
35+
36+ public static topLevelToJson(value: TopLevel): string {
37+ return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
38+ }
39+}
40+
41+function invalidValue(typ: any, val: any, key: any, parent: any = ''): never {
42+ const prettyTyp = prettyTypeName(typ);
43+ const parentText = parent ? ` on ${parent}` : '';
44+ const keyText = key ? ` for key "${key}"` : '';
45+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
46+}
47+
48+function prettyTypeName(typ: any): string {
49+ if (Array.isArray(typ)) {
50+ if (typ.length === 2 && typ[0] === undefined) {
51+ return `an optional ${prettyTypeName(typ[1])}`;
52+ } else {
53+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
54+ }
55+ } else if (typeof typ === "object" && typ.literal !== undefined) {
56+ return typ.literal;
57+ } else {
58+ return typeof typ;
59+ }
60+}
61+
62+function jsonToJSProps(typ: any): any {
63+ if (typ.jsonToJS === undefined) {
64+ const map: any = {};
65+ typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
66+ typ.jsonToJS = map;
67+ }
68+ return typ.jsonToJS;
69+}
70+
71+function jsToJSONProps(typ: any): any {
72+ if (typ.jsToJSON === undefined) {
73+ const map: any = {};
74+ typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
75+ typ.jsToJSON = map;
76+ }
77+ return typ.jsToJSON;
78+}
79+
80+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
81+ function transformPrimitive(typ: string, val: any): any {
82+ if (typeof typ === typeof val) return val;
83+ return invalidValue(typ, val, key, parent);
84+ }
85+
86+ function transformUnion(typs: any[], val: any): any {
87+ // val must validate against one typ in typs
88+ const l = typs.length;
89+ for (let i = 0; i < l; i++) {
90+ const typ = typs[i];
91+ try {
92+ return transform(val, typ, getProps);
93+ } catch (_) {}
94+ }
95+ return invalidValue(typs, val, key, parent);
96+ }
97+
98+ function transformEnum(cases: string[], val: any): any {
99+ if (cases.indexOf(val) !== -1) return val;
100+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
101+ }
102+
103+ function transformArray(typ: any, val: any): any {
104+ // val must be an array with no invalid elements
105+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
106+ return val.map(el => transform(el, typ, getProps));
107+ }
108+
109+ function transformDate(val: any): any {
110+ if (val === null) {
111+ return null;
112+ }
113+ const d = new Date(val);
114+ if (isNaN(d.valueOf())) {
115+ return invalidValue(l("Date"), val, key, parent);
116+ }
117+ return d;
118+ }
119+
120+ function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
121+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
122+ return invalidValue(l(ref || "object"), val, key, parent);
123+ }
124+ const result: any = {};
125+ Object.getOwnPropertyNames(props).forEach(key => {
126+ const prop = props[key];
127+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
128+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
129+ });
130+ Object.getOwnPropertyNames(val).forEach(key => {
131+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
132+ result[key] = transform(val[key], additional, getProps, key, ref);
133+ }
134+ });
135+ return result;
136+ }
137+
138+ if (typ === "any") return val;
139+ if (typ === null) {
140+ if (val === null) return val;
141+ return invalidValue(typ, val, key, parent);
142+ }
143+ if (typ === false) return invalidValue(typ, val, key, parent);
144+ let ref: any = undefined;
145+ while (typeof typ === "object" && typ.ref !== undefined) {
146+ ref = typ.ref;
147+ typ = typeMap[typ.ref];
148+ }
149+ if (Array.isArray(typ)) return transformEnum(typ, val);
150+ if (typeof typ === "object") {
151+ return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
152+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
153+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
154+ : invalidValue(typ, val, key, parent);
155+ }
156+ // Numbers can be parsed by Date but shouldn't be.
157+ if (typ === Date && typeof val !== "number") return transformDate(val);
158+ return transformPrimitive(typ, val);
159+}
160+
161+function cast<T>(val: any, typ: any): T {
162+ return transform(val, typ, jsonToJSProps);
163+}
164+
165+function uncast<T>(val: T, typ: any): any {
166+ return transform(val, typ, jsToJSONProps);
167+}
168+
169+function l(typ: any) {
170+ return { literal: typ };
171+}
172+
173+function a(typ: any) {
174+ return { arrayItems: typ };
175+}
176+
177+function u(...typs: any[]) {
178+ return { unionMembers: typs };
179+}
180+
181+function o(props: any[], additional: any) {
182+ return { props, additional };
183+}
184+
185+function m(additional: any) {
186+ const props: any[] = [];
187+ return { props, additional };
188+}
189+
190+function r(name: string) {
191+ return { ref: name };
192+}
193+
194+const typeMap: any = {
195+ "TopLevel": o([
196+ { json: "foo", js: "foo", typ: r("StateInfoXxx") },
197+ { json: "woo", js: "woo", typ: r("StateInfoWWW") },
198+ ], false),
199+ "StateInfoXxx": o([
200+ { json: "changeTime", js: "changeTime", typ: 3.14 },
201+ { json: "state", js: "state", typ: r("FooState") },
202+ ], false),
203+ "StateInfoWWW": o([
204+ { json: "changeTime", js: "changeTime", typ: 3.14 },
205+ { json: "state", js: "state", typ: r("WooState") },
206+ ], false),
207+ "FooState": [
208+ "xx",
209+ "yy",
210+ ],
211+ "WooState": [
212+ "asd",
213+ "qwe",
214+ "zxc",
215+ "tyu",
216+ ],
217+};
No generated files match these filters.