Test case
27 generated files · +2,242 −0test/inputs/schema/pattern-properties.schema
Aschema-cplusplusdefault / quicktype.hpp+151 −0
| @@ -0,0 +1,151 @@ | ||
| 1 | +// To parse this JSON data, first install | |
| 2 | +// | |
| 3 | +// json.hpp https://github.com/nlohmann/json | |
| 4 | +// | |
| 5 | +// Then include this file, and then do | |
| 6 | +// | |
| 7 | +// TopLevel data = nlohmann::json::parse(jsonString); | |
| 8 | + | |
| 9 | +#pragma once | |
| 10 | + | |
| 11 | +#include <optional> | |
| 12 | +#include "json.hpp" | |
| 13 | + | |
| 14 | +#include <optional> | |
| 15 | +#include <stdexcept> | |
| 16 | +#include <regex> | |
| 17 | + | |
| 18 | +#ifndef NLOHMANN_OPT_HELPER | |
| 19 | +#define NLOHMANN_OPT_HELPER | |
| 20 | +namespace nlohmann { | |
| 21 | + template <typename T> | |
| 22 | + struct adl_serializer<std::shared_ptr<T>> { | |
| 23 | + static void to_json(json & j, const std::shared_ptr<T> & opt) { | |
| 24 | + if (!opt) j = nullptr; else j = *opt; | |
| 25 | + } | |
| 26 | + | |
| 27 | + static std::shared_ptr<T> from_json(const json & j) { | |
| 28 | + if (j.is_null()) return std::shared_ptr<T>(); else return std::make_shared<T>(j.get<T>()); | |
| 29 | + } | |
| 30 | + }; | |
| 31 | + template <typename T> | |
| 32 | + struct adl_serializer<std::optional<T>> { | |
| 33 | + static void to_json(json & j, const std::optional<T> & opt) { | |
| 34 | + if (!opt) j = nullptr; else j = *opt; | |
| 35 | + } | |
| 36 | + | |
| 37 | + static std::optional<T> from_json(const json & j) { | |
| 38 | + if (j.is_null()) return std::optional<T>(); else return std::make_optional<T>(j.get<T>()); | |
| 39 | + } | |
| 40 | + }; | |
| 41 | +} | |
| 42 | +#endif | |
| 43 | + | |
| 44 | +namespace quicktype { | |
| 45 | + using nlohmann::json; | |
| 46 | + | |
| 47 | + #ifndef NLOHMANN_UNTYPED_quicktype_HELPER | |
| 48 | + #define NLOHMANN_UNTYPED_quicktype_HELPER | |
| 49 | + inline json get_untyped(const json & j, const char * property) { | |
| 50 | + if (j.find(property) != j.end()) { | |
| 51 | + return j.at(property).get<json>(); | |
| 52 | + } | |
| 53 | + return json(); | |
| 54 | + } | |
| 55 | + | |
| 56 | + inline json get_untyped(const json & j, std::string property) { | |
| 57 | + return get_untyped(j, property.data()); | |
| 58 | + } | |
| 59 | + #endif | |
| 60 | + | |
| 61 | + #ifndef NLOHMANN_OPTIONAL_quicktype_HELPER | |
| 62 | + #define NLOHMANN_OPTIONAL_quicktype_HELPER | |
| 63 | + template <typename T> | |
| 64 | + inline std::shared_ptr<T> get_heap_optional(const json & j, const char * property) { | |
| 65 | + auto it = j.find(property); | |
| 66 | + if (it != j.end() && !it->is_null()) { | |
| 67 | + return j.at(property).get<std::shared_ptr<T>>(); | |
| 68 | + } | |
| 69 | + return std::shared_ptr<T>(); | |
| 70 | + } | |
| 71 | + | |
| 72 | + template <typename T> | |
| 73 | + inline std::shared_ptr<T> get_heap_optional(const json & j, std::string property) { | |
| 74 | + return get_heap_optional<T>(j, property.data()); | |
| 75 | + } | |
| 76 | + template <typename T> | |
| 77 | + inline std::optional<T> get_stack_optional(const json & j, const char * property) { | |
| 78 | + auto it = j.find(property); | |
| 79 | + if (it != j.end() && !it->is_null()) { | |
| 80 | + return j.at(property).get<std::optional<T>>(); | |
| 81 | + } | |
| 82 | + return std::optional<T>(); | |
| 83 | + } | |
| 84 | + | |
| 85 | + template <typename T> | |
| 86 | + inline std::optional<T> get_stack_optional(const json & j, std::string property) { | |
| 87 | + return get_stack_optional<T>(j, property.data()); | |
| 88 | + } | |
| 89 | + #endif | |
| 90 | + | |
| 91 | + class Alternator { | |
| 92 | + public: | |
| 93 | + Alternator() = default; | |
| 94 | + virtual ~Alternator() = default; | |
| 95 | + | |
| 96 | + private: | |
| 97 | + std::optional<std::string> name; | |
| 98 | + std::optional<double> voltage; | |
| 99 | + | |
| 100 | + public: | |
| 101 | + const std::optional<std::string> & get_name() const { return name; } | |
| 102 | + std::optional<std::string> & get_mutable_name() { return name; } | |
| 103 | + void set_name(const std::optional<std::string> & value) { this->name = value; } | |
| 104 | + | |
| 105 | + const std::optional<double> & get_voltage() const { return voltage; } | |
| 106 | + std::optional<double> & get_mutable_voltage() { return voltage; } | |
| 107 | + void set_voltage(const std::optional<double> & value) { this->voltage = value; } | |
| 108 | + }; | |
| 109 | + | |
| 110 | + class TopLevel { | |
| 111 | + public: | |
| 112 | + TopLevel() = default; | |
| 113 | + virtual ~TopLevel() = default; | |
| 114 | + | |
| 115 | + private: | |
| 116 | + std::optional<std::map<std::string, Alternator>> alternators; | |
| 117 | + | |
| 118 | + public: | |
| 119 | + const std::optional<std::map<std::string, Alternator>> & get_alternators() const { return alternators; } | |
| 120 | + std::optional<std::map<std::string, Alternator>> & get_mutable_alternators() { return alternators; } | |
| 121 | + void set_alternators(const std::optional<std::map<std::string, Alternator>> & value) { this->alternators = value; } | |
| 122 | + }; | |
| 123 | +} | |
| 124 | + | |
| 125 | +namespace quicktype { | |
| 126 | + void from_json(const json & j, Alternator & x); | |
| 127 | + void to_json(json & j, const Alternator & x); | |
| 128 | + | |
| 129 | + void from_json(const json & j, TopLevel & x); | |
| 130 | + void to_json(json & j, const TopLevel & x); | |
| 131 | + | |
| 132 | + inline void from_json(const json & j, Alternator& x) { | |
| 133 | + x.set_name(get_stack_optional<std::string>(j, "name")); | |
| 134 | + x.set_voltage(get_stack_optional<double>(j, "voltage")); | |
| 135 | + } | |
| 136 | + | |
| 137 | + inline void to_json(json & j, const Alternator & x) { | |
| 138 | + j = json::object(); | |
| 139 | + j["name"] = x.get_name(); | |
| 140 | + j["voltage"] = x.get_voltage(); | |
| 141 | + } | |
| 142 | + | |
| 143 | + inline void from_json(const json & j, TopLevel& x) { | |
| 144 | + x.set_alternators(get_stack_optional<std::map<std::string, Alternator>>(j, "alternators")); | |
| 145 | + } | |
| 146 | + | |
| 147 | + inline void to_json(json & j, const TopLevel & x) { | |
| 148 | + j = json::object(); | |
| 149 | + j["alternators"] = x.get_alternators(); | |
| 150 | + } | |
| 151 | +} |
Aschema-csharp-recordsdefault / QuickType.cs+70 −0
| @@ -0,0 +1,70 @@ | ||
| 1 | +// <auto-generated /> | |
| 2 | +// | |
| 3 | +// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do: | |
| 4 | +// | |
| 5 | +// using QuickType; | |
| 6 | +// | |
| 7 | +// var topLevel = TopLevel.FromJson(jsonString); | |
| 8 | +#nullable enable | |
| 9 | +#pragma warning disable CS8618 | |
| 10 | +#pragma warning disable CS8601 | |
| 11 | +#pragma warning disable CS8602 | |
| 12 | +#pragma warning disable CS8603 | |
| 13 | +#pragma warning disable CS8604 | |
| 14 | +#pragma warning disable CS8625 | |
| 15 | +#pragma warning disable CS8765 | |
| 16 | + | |
| 17 | +namespace QuickType | |
| 18 | +{ | |
| 19 | + using System; | |
| 20 | + using System.Collections.Generic; | |
| 21 | + | |
| 22 | + using System.Globalization; | |
| 23 | + using Newtonsoft.Json; | |
| 24 | + using Newtonsoft.Json.Converters; | |
| 25 | + | |
| 26 | + public partial record TopLevel | |
| 27 | + { | |
| 28 | + [JsonProperty("alternators", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 29 | + public Dictionary<string, Alternator>? Alternators { get; set; } | |
| 30 | + } | |
| 31 | + | |
| 32 | + public partial record Alternator | |
| 33 | + { | |
| 34 | + [JsonProperty("name", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 35 | + public string? Name { get; set; } | |
| 36 | + | |
| 37 | + [JsonProperty("voltage", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 38 | + public double? Voltage { get; set; } | |
| 39 | + } | |
| 40 | + | |
| 41 | + public partial record TopLevel | |
| 42 | + { | |
| 43 | + public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings); | |
| 44 | + } | |
| 45 | + | |
| 46 | + public static partial class Serialize | |
| 47 | + { | |
| 48 | + public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings); | |
| 49 | + } | |
| 50 | + | |
| 51 | + internal static partial class Converter | |
| 52 | + { | |
| 53 | + public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings | |
| 54 | + { | |
| 55 | + MetadataPropertyHandling = MetadataPropertyHandling.Ignore, | |
| 56 | + DateParseHandling = DateParseHandling.None, | |
| 57 | + Converters = | |
| 58 | + { | |
| 59 | + new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal } | |
| 60 | + }, | |
| 61 | + }; | |
| 62 | + } | |
| 63 | +} | |
| 64 | +#pragma warning restore CS8618 | |
| 65 | +#pragma warning restore CS8601 | |
| 66 | +#pragma warning restore CS8602 | |
| 67 | +#pragma warning restore CS8603 | |
| 68 | +#pragma warning restore CS8604 | |
| 69 | +#pragma warning restore CS8625 | |
| 70 | +#pragma warning restore CS8765 |
Aschema-csharp-SystemTextJsondefault / QuickType.cs+177 −0
| @@ -0,0 +1,177 @@ | ||
| 1 | +// <auto-generated /> | |
| 2 | +// | |
| 3 | +// To parse this JSON data, add NuGet 'System.Text.Json' then do: | |
| 4 | +// | |
| 5 | +// using QuickType; | |
| 6 | +// | |
| 7 | +// var topLevel = TopLevel.FromJson(jsonString); | |
| 8 | +#nullable enable | |
| 9 | +#pragma warning disable CS8618 | |
| 10 | +#pragma warning disable CS8601 | |
| 11 | +#pragma warning disable CS8602 | |
| 12 | +#pragma warning disable CS8603 | |
| 13 | + | |
| 14 | +namespace QuickType | |
| 15 | +{ | |
| 16 | + using System; | |
| 17 | + using System.Collections.Generic; | |
| 18 | + | |
| 19 | + using System.Text.Json; | |
| 20 | + using System.Text.Json.Serialization; | |
| 21 | + using System.Globalization; | |
| 22 | + | |
| 23 | + public partial class TopLevel | |
| 24 | + { | |
| 25 | + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] | |
| 26 | + [JsonPropertyName("alternators")] | |
| 27 | + public Dictionary<string, Alternator>? Alternators { get; set; } | |
| 28 | + } | |
| 29 | + | |
| 30 | + public partial class Alternator | |
| 31 | + { | |
| 32 | + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] | |
| 33 | + [JsonPropertyName("name")] | |
| 34 | + public string? Name { get; set; } | |
| 35 | + | |
| 36 | + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] | |
| 37 | + [JsonPropertyName("voltage")] | |
| 38 | + public double? Voltage { get; set; } | |
| 39 | + } | |
| 40 | + | |
| 41 | + public partial class TopLevel | |
| 42 | + { | |
| 43 | + public static TopLevel FromJson(string json) => JsonSerializer.Deserialize<TopLevel>(json, QuickType.Converter.Settings); | |
| 44 | + } | |
| 45 | + | |
| 46 | + public static partial class Serialize | |
| 47 | + { | |
| 48 | + public static string ToJson(this TopLevel self) => JsonSerializer.Serialize(self, QuickType.Converter.Settings); | |
| 49 | + } | |
| 50 | + | |
| 51 | + internal static partial class Converter | |
| 52 | + { | |
| 53 | + public static readonly JsonSerializerOptions Settings = new(JsonSerializerDefaults.General) | |
| 54 | + { | |
| 55 | + Converters = | |
| 56 | + { | |
| 57 | + new DateOnlyConverter(), | |
| 58 | + new TimeOnlyConverter(), | |
| 59 | + IsoDateTimeOffsetConverter.Singleton | |
| 60 | + }, | |
| 61 | + }; | |
| 62 | + } | |
| 63 | + | |
| 64 | + public class DateOnlyConverter : JsonConverter<DateOnly> | |
| 65 | + { | |
| 66 | + private readonly string serializationFormat; | |
| 67 | + public DateOnlyConverter() : this(null) { } | |
| 68 | + | |
| 69 | + public DateOnlyConverter(string? serializationFormat) | |
| 70 | + { | |
| 71 | + this.serializationFormat = serializationFormat ?? "yyyy-MM-dd"; | |
| 72 | + } | |
| 73 | + | |
| 74 | + public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
| 75 | + { | |
| 76 | + var value = reader.GetString(); | |
| 77 | + return DateOnly.Parse(value!); | |
| 78 | + } | |
| 79 | + | |
| 80 | + public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options) | |
| 81 | + => writer.WriteStringValue(value.ToString(serializationFormat)); | |
| 82 | + } | |
| 83 | + | |
| 84 | + public class TimeOnlyConverter : JsonConverter<TimeOnly> | |
| 85 | + { | |
| 86 | + private readonly string serializationFormat; | |
| 87 | + | |
| 88 | + public TimeOnlyConverter() : this(null) { } | |
| 89 | + | |
| 90 | + public TimeOnlyConverter(string? serializationFormat) | |
| 91 | + { | |
| 92 | + this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff"; | |
| 93 | + } | |
| 94 | + | |
| 95 | + public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
| 96 | + { | |
| 97 | + var value = reader.GetString(); | |
| 98 | + return TimeOnly.Parse(value!); | |
| 99 | + } | |
| 100 | + | |
| 101 | + public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options) | |
| 102 | + => writer.WriteStringValue(value.ToString(serializationFormat)); | |
| 103 | + } | |
| 104 | + | |
| 105 | + internal class IsoDateTimeOffsetConverter : JsonConverter<DateTimeOffset> | |
| 106 | + { | |
| 107 | + public override bool CanConvert(Type t) => t == typeof(DateTimeOffset); | |
| 108 | + | |
| 109 | + private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; | |
| 110 | + | |
| 111 | + private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind; | |
| 112 | + private string? _dateTimeFormat; | |
| 113 | + private CultureInfo? _culture; | |
| 114 | + | |
| 115 | + public DateTimeStyles DateTimeStyles | |
| 116 | + { | |
| 117 | + get => _dateTimeStyles; | |
| 118 | + set => _dateTimeStyles = value; | |
| 119 | + } | |
| 120 | + | |
| 121 | + public string? DateTimeFormat | |
| 122 | + { | |
| 123 | + get => _dateTimeFormat ?? string.Empty; | |
| 124 | + set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value; | |
| 125 | + } | |
| 126 | + | |
| 127 | + public CultureInfo Culture | |
| 128 | + { | |
| 129 | + get => _culture ?? CultureInfo.CurrentCulture; | |
| 130 | + set => _culture = value; | |
| 131 | + } | |
| 132 | + | |
| 133 | + public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options) | |
| 134 | + { | |
| 135 | + string text; | |
| 136 | + | |
| 137 | + | |
| 138 | + if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal | |
| 139 | + || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal) | |
| 140 | + { | |
| 141 | + value = value.ToUniversalTime(); | |
| 142 | + } | |
| 143 | + | |
| 144 | + text = value.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture); | |
| 145 | + | |
| 146 | + writer.WriteStringValue(text); | |
| 147 | + } | |
| 148 | + | |
| 149 | + public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
| 150 | + { | |
| 151 | + string? dateText = reader.GetString(); | |
| 152 | + | |
| 153 | + if (string.IsNullOrEmpty(dateText) == false) | |
| 154 | + { | |
| 155 | + if (!string.IsNullOrEmpty(_dateTimeFormat)) | |
| 156 | + { | |
| 157 | + return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles); | |
| 158 | + } | |
| 159 | + else | |
| 160 | + { | |
| 161 | + return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles); | |
| 162 | + } | |
| 163 | + } | |
| 164 | + else | |
| 165 | + { | |
| 166 | + return default(DateTimeOffset); | |
| 167 | + } | |
| 168 | + } | |
| 169 | + | |
| 170 | + | |
| 171 | + public static readonly IsoDateTimeOffsetConverter Singleton = new IsoDateTimeOffsetConverter(); | |
| 172 | + } | |
| 173 | +} | |
| 174 | +#pragma warning restore CS8618 | |
| 175 | +#pragma warning restore CS8601 | |
| 176 | +#pragma warning restore CS8602 | |
| 177 | +#pragma warning restore CS8603 |
Aschema-csharpdefault / QuickType.cs+70 −0
| @@ -0,0 +1,70 @@ | ||
| 1 | +// <auto-generated /> | |
| 2 | +// | |
| 3 | +// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do: | |
| 4 | +// | |
| 5 | +// using QuickType; | |
| 6 | +// | |
| 7 | +// var topLevel = TopLevel.FromJson(jsonString); | |
| 8 | +#nullable enable | |
| 9 | +#pragma warning disable CS8618 | |
| 10 | +#pragma warning disable CS8601 | |
| 11 | +#pragma warning disable CS8602 | |
| 12 | +#pragma warning disable CS8603 | |
| 13 | +#pragma warning disable CS8604 | |
| 14 | +#pragma warning disable CS8625 | |
| 15 | +#pragma warning disable CS8765 | |
| 16 | + | |
| 17 | +namespace QuickType | |
| 18 | +{ | |
| 19 | + using System; | |
| 20 | + using System.Collections.Generic; | |
| 21 | + | |
| 22 | + using System.Globalization; | |
| 23 | + using Newtonsoft.Json; | |
| 24 | + using Newtonsoft.Json.Converters; | |
| 25 | + | |
| 26 | + public partial class TopLevel | |
| 27 | + { | |
| 28 | + [JsonProperty("alternators", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 29 | + public Dictionary<string, Alternator>? Alternators { get; set; } | |
| 30 | + } | |
| 31 | + | |
| 32 | + public partial class Alternator | |
| 33 | + { | |
| 34 | + [JsonProperty("name", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 35 | + public string? Name { get; set; } | |
| 36 | + | |
| 37 | + [JsonProperty("voltage", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 38 | + public double? Voltage { get; set; } | |
| 39 | + } | |
| 40 | + | |
| 41 | + public partial class TopLevel | |
| 42 | + { | |
| 43 | + public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings); | |
| 44 | + } | |
| 45 | + | |
| 46 | + public static partial class Serialize | |
| 47 | + { | |
| 48 | + public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings); | |
| 49 | + } | |
| 50 | + | |
| 51 | + internal static partial class Converter | |
| 52 | + { | |
| 53 | + public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings | |
| 54 | + { | |
| 55 | + MetadataPropertyHandling = MetadataPropertyHandling.Ignore, | |
| 56 | + DateParseHandling = DateParseHandling.None, | |
| 57 | + Converters = | |
| 58 | + { | |
| 59 | + new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal } | |
| 60 | + }, | |
| 61 | + }; | |
| 62 | + } | |
| 63 | +} | |
| 64 | +#pragma warning restore CS8618 | |
| 65 | +#pragma warning restore CS8601 | |
| 66 | +#pragma warning restore CS8602 | |
| 67 | +#pragma warning restore CS8603 | |
| 68 | +#pragma warning restore CS8604 | |
| 69 | +#pragma warning restore CS8625 | |
| 70 | +#pragma warning restore CS8765 |
Aschema-dartdefault / TopLevel.dart+45 −0
| @@ -0,0 +1,45 @@ | ||
| 1 | +// To parse this JSON data, do | |
| 2 | +// | |
| 3 | +// final topLevel = topLevelFromJson(jsonString); | |
| 4 | + | |
| 5 | +import 'dart:convert'; | |
| 6 | + | |
| 7 | +TopLevel topLevelFromJson(String str) => TopLevel.fromJson(json.decode(str)); | |
| 8 | + | |
| 9 | +String topLevelToJson(TopLevel data) => json.encode(data.toJson()); | |
| 10 | + | |
| 11 | +class TopLevel { | |
| 12 | + final Map<String, Alternator>? alternators; | |
| 13 | + | |
| 14 | + TopLevel({ | |
| 15 | + this.alternators, | |
| 16 | + }); | |
| 17 | + | |
| 18 | + factory TopLevel.fromJson(Map<String, dynamic> json) => TopLevel( | |
| 19 | + alternators: Map.from(json["alternators"]!).map((k, v) => MapEntry<String, Alternator>(k, Alternator.fromJson(v))), | |
| 20 | + ); | |
| 21 | + | |
| 22 | + Map<String, dynamic> toJson() => { | |
| 23 | + "alternators": Map.from(alternators!).map((k, v) => MapEntry<String, dynamic>(k, v.toJson())), | |
| 24 | + }; | |
| 25 | +} | |
| 26 | + | |
| 27 | +class Alternator { | |
| 28 | + final String? name; | |
| 29 | + final double? voltage; | |
| 30 | + | |
| 31 | + Alternator({ | |
| 32 | + this.name, | |
| 33 | + this.voltage, | |
| 34 | + }); | |
| 35 | + | |
| 36 | + factory Alternator.fromJson(Map<String, dynamic> json) => Alternator( | |
| 37 | + name: json["name"], | |
| 38 | + voltage: json["voltage"]?.toDouble(), | |
| 39 | + ); | |
| 40 | + | |
| 41 | + Map<String, dynamic> toJson() => { | |
| 42 | + "name": name, | |
| 43 | + "voltage": voltage, | |
| 44 | + }; | |
| 45 | +} |
Aschema-elmdefault / QuickType.elm+70 −0
| @@ -0,0 +1,70 @@ | ||
| 1 | +-- To decode the JSON data, add this file to your project, run | |
| 2 | +-- | |
| 3 | +-- elm install NoRedInk/elm-json-decode-pipeline | |
| 4 | +-- | |
| 5 | +-- add these imports | |
| 6 | +-- | |
| 7 | +-- import Json.Decode exposing (decodeString) | |
| 8 | +-- import QuickType exposing (quickType) | |
| 9 | +-- | |
| 10 | +-- and you're off to the races with | |
| 11 | +-- | |
| 12 | +-- decodeString quickType myJsonString | |
| 13 | + | |
| 14 | +module QuickType exposing | |
| 15 | + ( QuickType | |
| 16 | + , quickTypeToString | |
| 17 | + , quickType | |
| 18 | + , Alternator | |
| 19 | + ) | |
| 20 | + | |
| 21 | +import Json.Decode as Jdec | |
| 22 | +import Json.Decode.Pipeline as Jpipe | |
| 23 | +import Json.Encode as Jenc | |
| 24 | +import Dict exposing (Dict) | |
| 25 | + | |
| 26 | +type alias QuickType = | |
| 27 | + { alternators : Maybe (Dict String Alternator) | |
| 28 | + } | |
| 29 | + | |
| 30 | +type alias Alternator = | |
| 31 | + { name : Maybe String | |
| 32 | + , voltage : Maybe Float | |
| 33 | + } | |
| 34 | + | |
| 35 | +-- decoders and encoders | |
| 36 | + | |
| 37 | +quickTypeToString : QuickType -> String | |
| 38 | +quickTypeToString r = Jenc.encode 0 (encodeQuickType r) | |
| 39 | + | |
| 40 | +quickType : Jdec.Decoder QuickType | |
| 41 | +quickType = | |
| 42 | + Jdec.succeed QuickType | |
| 43 | + |> Jpipe.optional "alternators" (Jdec.nullable (Jdec.dict alternator)) Nothing | |
| 44 | + | |
| 45 | +encodeQuickType : QuickType -> Jenc.Value | |
| 46 | +encodeQuickType x = | |
| 47 | + Jenc.object | |
| 48 | + [ ("alternators", makeNullableEncoder (Jenc.dict identity encodeAlternator) x.alternators) | |
| 49 | + ] | |
| 50 | + | |
| 51 | +alternator : Jdec.Decoder Alternator | |
| 52 | +alternator = | |
| 53 | + Jdec.succeed Alternator | |
| 54 | + |> Jpipe.optional "name" (Jdec.nullable Jdec.string) Nothing | |
| 55 | + |> Jpipe.optional "voltage" (Jdec.nullable Jdec.float) Nothing | |
| 56 | + | |
| 57 | +encodeAlternator : Alternator -> Jenc.Value | |
| 58 | +encodeAlternator x = | |
| 59 | + Jenc.object | |
| 60 | + [ ("name", makeNullableEncoder Jenc.string x.name) | |
| 61 | + , ("voltage", makeNullableEncoder Jenc.float x.voltage) | |
| 62 | + ] | |
| 63 | + | |
| 64 | +--- encoder helpers | |
| 65 | + | |
| 66 | +makeNullableEncoder : (a -> Jenc.Value) -> Maybe a -> Jenc.Value | |
| 67 | +makeNullableEncoder f m = | |
| 68 | + case m of | |
| 69 | + Just x -> f x | |
| 70 | + Nothing -> Jenc.null |
Aschema-flowdefault / TopLevel.js+199 −0
| @@ -0,0 +1,199 @@ | ||
| 1 | +// @flow | |
| 2 | + | |
| 3 | +// To parse this data: | |
| 4 | +// | |
| 5 | +// const Convert = require("./TopLevel"); | |
| 6 | +// | |
| 7 | +// const topLevel = Convert.toTopLevel(json); | |
| 8 | +// | |
| 9 | +// These functions will throw an error if the JSON doesn't | |
| 10 | +// match the expected interface, even if the JSON is valid. | |
| 11 | + | |
| 12 | +export type TopLevel = { | |
| 13 | + alternators?: { [key: string]: Alternator }; | |
| 14 | + [property: string]: mixed; | |
| 15 | +}; | |
| 16 | + | |
| 17 | +export type Alternator = { | |
| 18 | + name?: string; | |
| 19 | + voltage?: number; | |
| 20 | + [property: string]: mixed; | |
| 21 | +}; | |
| 22 | + | |
| 23 | +// Converts JSON strings to/from your types | |
| 24 | +// and asserts the results of JSON.parse at runtime | |
| 25 | +function toTopLevel(json: string): TopLevel { | |
| 26 | + return cast(JSON.parse(json), r("TopLevel")); | |
| 27 | +} | |
| 28 | + | |
| 29 | +function topLevelToJson(value: TopLevel): string { | |
| 30 | + return JSON.stringify(uncast(value, r("TopLevel")), null, 2); | |
| 31 | +} | |
| 32 | + | |
| 33 | +function invalidValue(typ: any, val: any, key: any, parent: any = '') { | |
| 34 | + const prettyTyp = prettyTypeName(typ); | |
| 35 | + const parentText = parent ? ` on ${parent}` : ''; | |
| 36 | + const keyText = key ? ` for key "${key}"` : ''; | |
| 37 | + throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`); | |
| 38 | +} | |
| 39 | + | |
| 40 | +function prettyTypeName(typ: any): string { | |
| 41 | + if (Array.isArray(typ)) { | |
| 42 | + if (typ.length === 2 && typ[0] === undefined) { | |
| 43 | + return `an optional ${prettyTypeName(typ[1])}`; | |
| 44 | + } else { | |
| 45 | + return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`; | |
| 46 | + } | |
| 47 | + } else if (typeof typ === "object" && typ.literal !== undefined) { | |
| 48 | + return typ.literal; | |
| 49 | + } else { | |
| 50 | + return typeof typ; | |
| 51 | + } | |
| 52 | +} | |
| 53 | + | |
| 54 | +function jsonToJSProps(typ: any): any { | |
| 55 | + if (typ.jsonToJS === undefined) { | |
| 56 | + const map: any = {}; | |
| 57 | + typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ }); | |
| 58 | + typ.jsonToJS = map; | |
| 59 | + } | |
| 60 | + return typ.jsonToJS; | |
| 61 | +} | |
| 62 | + | |
| 63 | +function jsToJSONProps(typ: any): any { | |
| 64 | + if (typ.jsToJSON === undefined) { | |
| 65 | + const map: any = {}; | |
| 66 | + typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ }); | |
| 67 | + typ.jsToJSON = map; | |
| 68 | + } | |
| 69 | + return typ.jsToJSON; | |
| 70 | +} | |
| 71 | + | |
| 72 | +function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any { | |
| 73 | + function transformPrimitive(typ: string, val: any): any { | |
| 74 | + if (typeof typ === typeof val) return val; | |
| 75 | + return invalidValue(typ, val, key, parent); | |
| 76 | + } | |
| 77 | + | |
| 78 | + function transformUnion(typs: any[], val: any): any { | |
| 79 | + // val must validate against one typ in typs | |
| 80 | + const l = typs.length; | |
| 81 | + for (let i = 0; i < l; i++) { | |
| 82 | + const typ = typs[i]; | |
| 83 | + try { | |
| 84 | + return transform(val, typ, getProps); | |
| 85 | + } catch (_) {} | |
| 86 | + } | |
| 87 | + return invalidValue(typs, val, key, parent); | |
| 88 | + } | |
| 89 | + | |
| 90 | + function transformEnum(cases: string[], val: any): any { | |
| 91 | + if (cases.indexOf(val) !== -1) return val; | |
| 92 | + return invalidValue(cases.map(a => { return l(a); }), val, key, parent); | |
| 93 | + } | |
| 94 | + | |
| 95 | + function transformArray(typ: any, val: any): any { | |
| 96 | + // val must be an array with no invalid elements | |
| 97 | + if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent); | |
| 98 | + return val.map(el => transform(el, typ, getProps)); | |
| 99 | + } | |
| 100 | + | |
| 101 | + function transformDate(val: any): any { | |
| 102 | + if (val === null) { | |
| 103 | + return null; | |
| 104 | + } | |
| 105 | + const d = new Date(val); | |
| 106 | + if (isNaN(d.valueOf())) { | |
| 107 | + return invalidValue(l("Date"), val, key, parent); | |
| 108 | + } | |
| 109 | + return d; | |
| 110 | + } | |
| 111 | + | |
| 112 | + function transformObject(props: { [k: string]: any }, additional: any, val: any): any { | |
| 113 | + if (val === null || typeof val !== "object" || Array.isArray(val)) { | |
| 114 | + return invalidValue(l(ref || "object"), val, key, parent); | |
| 115 | + } | |
| 116 | + const result: any = {}; | |
| 117 | + Object.getOwnPropertyNames(props).forEach(key => { | |
| 118 | + const prop = props[key]; | |
| 119 | + const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined; | |
| 120 | + result[prop.key] = transform(v, prop.typ, getProps, key, ref); | |
| 121 | + }); | |
| 122 | + Object.getOwnPropertyNames(val).forEach(key => { | |
| 123 | + if (!Object.prototype.hasOwnProperty.call(props, key)) { | |
| 124 | + result[key] = transform(val[key], additional, getProps, key, ref); | |
| 125 | + } | |
| 126 | + }); | |
| 127 | + return result; | |
| 128 | + } | |
| 129 | + | |
| 130 | + if (typ === "any") return val; | |
| 131 | + if (typ === null) { | |
| 132 | + if (val === null) return val; | |
| 133 | + return invalidValue(typ, val, key, parent); | |
| 134 | + } | |
| 135 | + if (typ === false) return invalidValue(typ, val, key, parent); | |
| 136 | + let ref: any = undefined; | |
| 137 | + while (typeof typ === "object" && typ.ref !== undefined) { | |
| 138 | + ref = typ.ref; | |
| 139 | + typ = typeMap[typ.ref]; | |
| 140 | + } | |
| 141 | + if (Array.isArray(typ)) return transformEnum(typ, val); | |
| 142 | + if (typeof typ === "object") { | |
| 143 | + return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val) | |
| 144 | + : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val) | |
| 145 | + : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val) | |
| 146 | + : invalidValue(typ, val, key, parent); | |
| 147 | + } | |
| 148 | + // Numbers can be parsed by Date but shouldn't be. | |
| 149 | + if (typ === Date && typeof val !== "number") return transformDate(val); | |
| 150 | + return transformPrimitive(typ, val); | |
| 151 | +} | |
| 152 | + | |
| 153 | +function cast<T>(val: any, typ: any): T { | |
| 154 | + return transform(val, typ, jsonToJSProps); | |
| 155 | +} | |
| 156 | + | |
| 157 | +function uncast<T>(val: T, typ: any): any { | |
| 158 | + return transform(val, typ, jsToJSONProps); | |
| 159 | +} | |
| 160 | + | |
| 161 | +function l(typ: any) { | |
| 162 | + return { literal: typ }; | |
| 163 | +} | |
| 164 | + | |
| 165 | +function a(typ: any) { | |
| 166 | + return { arrayItems: typ }; | |
| 167 | +} | |
| 168 | + | |
| 169 | +function u(...typs: any[]) { | |
| 170 | + return { unionMembers: typs }; | |
| 171 | +} | |
| 172 | + | |
| 173 | +function o(props: any[], additional: any) { | |
| 174 | + return { props, additional }; | |
| 175 | +} | |
| 176 | + | |
| 177 | +function m(additional: any) { | |
| 178 | + const props: any[] = []; | |
| 179 | + return { props, additional }; | |
| 180 | +} | |
| 181 | + | |
| 182 | +function r(name: string) { | |
| 183 | + return { ref: name }; | |
| 184 | +} | |
| 185 | + | |
| 186 | +const typeMap: any = { | |
| 187 | + "TopLevel": o([ | |
| 188 | + { json: "alternators", js: "alternators", typ: u(undefined, m(r("Alternator"))) }, | |
| 189 | + ], "any"), | |
| 190 | + "Alternator": o([ | |
| 191 | + { json: "name", js: "name", typ: u(undefined, "") }, | |
| 192 | + { json: "voltage", js: "voltage", typ: u(undefined, 3.14) }, | |
| 193 | + ], "any"), | |
| 194 | +}; | |
| 195 | + | |
| 196 | +module.exports = { | |
| 197 | + "topLevelToJson": topLevelToJson, | |
| 198 | + "toTopLevel": toTopLevel, | |
| 199 | +}; |
Aschema-golangdefault / quicktype.go+28 −0
| @@ -0,0 +1,28 @@ | ||
| 1 | +// Code generated from JSON Schema using quicktype. DO NOT EDIT. | |
| 2 | +// To parse and unparse this JSON data, add this code to your project and do: | |
| 3 | +// | |
| 4 | +// topLevel, err := UnmarshalTopLevel(bytes) | |
| 5 | +// bytes, err = topLevel.Marshal() | |
| 6 | + | |
| 7 | +package main | |
| 8 | + | |
| 9 | +import "encoding/json" | |
| 10 | + | |
| 11 | +func UnmarshalTopLevel(data []byte) (TopLevel, error) { | |
| 12 | + var r TopLevel | |
| 13 | + err := json.Unmarshal(data, &r) | |
| 14 | + return r, err | |
| 15 | +} | |
| 16 | + | |
| 17 | +func (r *TopLevel) Marshal() ([]byte, error) { | |
| 18 | + return json.Marshal(r) | |
| 19 | +} | |
| 20 | + | |
| 21 | +type TopLevel struct { | |
| 22 | + Alternators map[string]Alternator `json:"alternators,omitempty"` | |
| 23 | +} | |
| 24 | + | |
| 25 | +type Alternator struct { | |
| 26 | + Name *string `json:"name,omitempty"` | |
| 27 | + Voltage *float64 `json:"voltage,omitempty"` | |
| 28 | +} |
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / Alternator.java+18 −0
| @@ -0,0 +1,18 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | + | |
| 5 | +public class Alternator { | |
| 6 | + private String name; | |
| 7 | + private Double voltage; | |
| 8 | + | |
| 9 | + @JsonProperty("name") | |
| 10 | + public String getName() { return name; } | |
| 11 | + @JsonProperty("name") | |
| 12 | + public void setName(String value) { this.name = value; } | |
| 13 | + | |
| 14 | + @JsonProperty("voltage") | |
| 15 | + public Double getVoltage() { return voltage; } | |
| 16 | + @JsonProperty("voltage") | |
| 17 | + public void setVoltage(Double value) { this.voltage = value; } | |
| 18 | +} |
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / Converter.java+121 −0
| @@ -0,0 +1,121 @@ | ||
| 1 | +// To use this code, add the following Maven dependency to your project: | |
| 2 | +// | |
| 3 | +// | |
| 4 | +// com.fasterxml.jackson.core : jackson-databind : 2.9.0 | |
| 5 | +// | |
| 6 | +// | |
| 7 | +// Import this package: | |
| 8 | +// | |
| 9 | +// import io.quicktype.Converter; | |
| 10 | +// | |
| 11 | +// Then you can deserialize a JSON string with | |
| 12 | +// | |
| 13 | +// TopLevel data = Converter.fromJsonString(jsonString); | |
| 14 | + | |
| 15 | +package io.quicktype; | |
| 16 | + | |
| 17 | +import java.io.IOException; | |
| 18 | +import com.fasterxml.jackson.databind.*; | |
| 19 | +import com.fasterxml.jackson.databind.module.SimpleModule; | |
| 20 | +import com.fasterxml.jackson.core.JsonParser; | |
| 21 | +import com.fasterxml.jackson.core.JsonProcessingException; | |
| 22 | +import java.util.*; | |
| 23 | +import java.util.Date; | |
| 24 | +import java.text.SimpleDateFormat; | |
| 25 | + | |
| 26 | +public class Converter { | |
| 27 | + // Date-time helpers | |
| 28 | + | |
| 29 | + private static final String[] DATE_TIME_FORMATS = { | |
| 30 | + "yyyy-MM-dd'T'HH:mm:ss.SX", | |
| 31 | + "yyyy-MM-dd'T'HH:mm:ss.S", | |
| 32 | + "yyyy-MM-dd'T'HH:mm:ssX", | |
| 33 | + "yyyy-MM-dd'T'HH:mm:ss", | |
| 34 | + "yyyy-MM-dd HH:mm:ss.SX", | |
| 35 | + "yyyy-MM-dd HH:mm:ss.S", | |
| 36 | + "yyyy-MM-dd HH:mm:ssX", | |
| 37 | + "yyyy-MM-dd HH:mm:ss", | |
| 38 | + "HH:mm:ss.SZ", | |
| 39 | + "HH:mm:ss.S", | |
| 40 | + "HH:mm:ssZ", | |
| 41 | + "HH:mm:ss", | |
| 42 | + "yyyy-MM-dd", | |
| 43 | + }; | |
| 44 | + | |
| 45 | + public static Date parseAllDateTimeString(String str) { | |
| 46 | + for (String format : DATE_TIME_FORMATS) { | |
| 47 | + try { | |
| 48 | + return new SimpleDateFormat(format).parse(str); | |
| 49 | + } catch (Exception ex) { | |
| 50 | + // Ignored | |
| 51 | + } | |
| 52 | + } | |
| 53 | + return null; | |
| 54 | + } | |
| 55 | + | |
| 56 | + public static String serializeDateTime(Date datetime) { | |
| 57 | + return new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ").format(datetime); | |
| 58 | + } | |
| 59 | + | |
| 60 | + public static String serializeDate(Date datetime) { | |
| 61 | + return new SimpleDateFormat("yyyy-MM-dd").format(datetime); | |
| 62 | + } | |
| 63 | + | |
| 64 | + public static String serializeTime(Date datetime) { | |
| 65 | + return new SimpleDateFormat("hh:mm:ssZ").format(datetime); | |
| 66 | + } | |
| 67 | + // Serialize/deserialize helpers | |
| 68 | + | |
| 69 | + public static TopLevel fromJsonString(String json) throws IOException { | |
| 70 | + return getObjectReader().readValue(json); | |
| 71 | + } | |
| 72 | + | |
| 73 | + public static String toJsonString(TopLevel obj) throws JsonProcessingException { | |
| 74 | + return getObjectWriter().writeValueAsString(obj); | |
| 75 | + } | |
| 76 | + | |
| 77 | + private static ObjectReader reader; | |
| 78 | + private static ObjectWriter writer; | |
| 79 | + | |
| 80 | + private static void instantiateMapper() { | |
| 81 | + ObjectMapper mapper = new ObjectMapper(); | |
| 82 | + mapper.findAndRegisterModules(); | |
| 83 | + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); | |
| 84 | + mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); | |
| 85 | + SimpleModule module = new SimpleModule(); | |
| 86 | + module.addDeserializer(Date.class, new JsonDeserializer<Date>() { | |
| 87 | + @Override | |
| 88 | + public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { | |
| 89 | + String value = jsonParser.getText(); | |
| 90 | + return Converter.parseAllDateTimeString(value); | |
| 91 | + } | |
| 92 | + }); | |
| 93 | + module.addDeserializer(Date.class, new JsonDeserializer<Date>() { | |
| 94 | + @Override | |
| 95 | + public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { | |
| 96 | + String value = jsonParser.getText(); | |
| 97 | + return Converter.parseAllDateTimeString(value); | |
| 98 | + } | |
| 99 | + }); | |
| 100 | + module.addDeserializer(Date.class, new JsonDeserializer<Date>() { | |
| 101 | + @Override | |
| 102 | + public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { | |
| 103 | + String value = jsonParser.getText(); | |
| 104 | + return Converter.parseAllDateTimeString(value); | |
| 105 | + } | |
| 106 | + }); | |
| 107 | + mapper.registerModule(module); | |
| 108 | + reader = mapper.readerFor(TopLevel.class); | |
| 109 | + writer = mapper.writerFor(TopLevel.class); | |
| 110 | + } | |
| 111 | + | |
| 112 | + private static ObjectReader getObjectReader() { | |
| 113 | + if (reader == null) instantiateMapper(); | |
| 114 | + return reader; | |
| 115 | + } | |
| 116 | + | |
| 117 | + private static ObjectWriter getObjectWriter() { | |
| 118 | + if (writer == null) instantiateMapper(); | |
| 119 | + return writer; | |
| 120 | + } | |
| 121 | +} |
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / TopLevel.java+13 −0
| @@ -0,0 +1,13 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | +import java.util.Map; | |
| 5 | + | |
| 6 | +public class TopLevel { | |
| 7 | + private Map<String, Alternator> alternators; | |
| 8 | + | |
| 9 | + @JsonProperty("alternators") | |
| 10 | + public Map<String, Alternator> getAlternators() { return alternators; } | |
| 11 | + @JsonProperty("alternators") | |
| 12 | + public void setAlternators(Map<String, Alternator> value) { this.alternators = value; } | |
| 13 | +} |
Aschema-java-lombokdefault / src / main / java / io / quicktype / Alternator.java+18 −0
| @@ -0,0 +1,18 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | + | |
| 5 | +public class Alternator { | |
| 6 | + private String name; | |
| 7 | + private Double voltage; | |
| 8 | + | |
| 9 | + @JsonProperty("name") | |
| 10 | + public String getName() { return name; } | |
| 11 | + @JsonProperty("name") | |
| 12 | + public void setName(String value) { this.name = value; } | |
| 13 | + | |
| 14 | + @JsonProperty("voltage") | |
| 15 | + public Double getVoltage() { return voltage; } | |
| 16 | + @JsonProperty("voltage") | |
| 17 | + public void setVoltage(Double value) { this.voltage = value; } | |
| 18 | +} |
Aschema-java-lombokdefault / src / main / java / io / quicktype / Converter.java+101 −0
| @@ -0,0 +1,101 @@ | ||
| 1 | +// To use this code, add the following Maven dependency to your project: | |
| 2 | +// | |
| 3 | +// | |
| 4 | +// com.fasterxml.jackson.core : jackson-databind : 2.9.0 | |
| 5 | +// com.fasterxml.jackson.datatype : jackson-datatype-jsr310 : 2.9.0 | |
| 6 | +// | |
| 7 | +// Import this package: | |
| 8 | +// | |
| 9 | +// import io.quicktype.Converter; | |
| 10 | +// | |
| 11 | +// Then you can deserialize a JSON string with | |
| 12 | +// | |
| 13 | +// TopLevel data = Converter.fromJsonString(jsonString); | |
| 14 | + | |
| 15 | +package io.quicktype; | |
| 16 | + | |
| 17 | +import java.io.IOException; | |
| 18 | +import com.fasterxml.jackson.databind.*; | |
| 19 | +import com.fasterxml.jackson.databind.module.SimpleModule; | |
| 20 | +import com.fasterxml.jackson.core.JsonParser; | |
| 21 | +import com.fasterxml.jackson.core.JsonProcessingException; | |
| 22 | +import java.util.*; | |
| 23 | +import java.time.LocalDate; | |
| 24 | +import java.time.OffsetDateTime; | |
| 25 | +import java.time.OffsetTime; | |
| 26 | +import java.time.ZoneOffset; | |
| 27 | +import java.time.ZonedDateTime; | |
| 28 | +import java.time.format.DateTimeFormatter; | |
| 29 | +import java.time.format.DateTimeFormatterBuilder; | |
| 30 | +import java.time.temporal.ChronoField; | |
| 31 | + | |
| 32 | +public class Converter { | |
| 33 | + // Date-time helpers | |
| 34 | + | |
| 35 | + private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder() | |
| 36 | + .appendOptional(DateTimeFormatter.ISO_DATE_TIME) | |
| 37 | + .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME) | |
| 38 | + .appendOptional(DateTimeFormatter.ISO_INSTANT) | |
| 39 | + .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX")) | |
| 40 | + .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX")) | |
| 41 | + .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) | |
| 42 | + .toFormatter() | |
| 43 | + .withZone(ZoneOffset.UTC); | |
| 44 | + | |
| 45 | + public static OffsetDateTime parseDateTimeString(String str) { | |
| 46 | + return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime(); | |
| 47 | + } | |
| 48 | + | |
| 49 | + private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder() | |
| 50 | + .appendOptional(DateTimeFormatter.ISO_TIME) | |
| 51 | + .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME) | |
| 52 | + .parseDefaulting(ChronoField.YEAR, 2020) | |
| 53 | + .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1) | |
| 54 | + .parseDefaulting(ChronoField.DAY_OF_MONTH, 1) | |
| 55 | + .toFormatter() | |
| 56 | + .withZone(ZoneOffset.UTC); | |
| 57 | + | |
| 58 | + public static OffsetTime parseTimeString(String str) { | |
| 59 | + return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime(); | |
| 60 | + } | |
| 61 | + // Serialize/deserialize helpers | |
| 62 | + | |
| 63 | + public static TopLevel fromJsonString(String json) throws IOException { | |
| 64 | + return getObjectReader().readValue(json); | |
| 65 | + } | |
| 66 | + | |
| 67 | + public static String toJsonString(TopLevel obj) throws JsonProcessingException { | |
| 68 | + return getObjectWriter().writeValueAsString(obj); | |
| 69 | + } | |
| 70 | + | |
| 71 | + private static ObjectReader reader; | |
| 72 | + private static ObjectWriter writer; | |
| 73 | + | |
| 74 | + private static void instantiateMapper() { | |
| 75 | + ObjectMapper mapper = new ObjectMapper(); | |
| 76 | + mapper.findAndRegisterModules(); | |
| 77 | + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); | |
| 78 | + mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); | |
| 79 | + SimpleModule module = new SimpleModule(); | |
| 80 | + module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() { | |
| 81 | + @Override | |
| 82 | + public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { | |
| 83 | + String value = jsonParser.getText(); | |
| 84 | + return Converter.parseDateTimeString(value); | |
| 85 | + } | |
| 86 | + }); | |
| 87 | + mapper.registerModule(module); | |
| 88 | + reader = mapper.readerFor(TopLevel.class); | |
| 89 | + writer = mapper.writerFor(TopLevel.class); | |
| 90 | + } | |
| 91 | + | |
| 92 | + private static ObjectReader getObjectReader() { | |
| 93 | + if (reader == null) instantiateMapper(); | |
| 94 | + return reader; | |
| 95 | + } | |
| 96 | + | |
| 97 | + private static ObjectWriter getObjectWriter() { | |
| 98 | + if (writer == null) instantiateMapper(); | |
| 99 | + return writer; | |
| 100 | + } | |
| 101 | +} |
Aschema-java-lombokdefault / src / main / java / io / quicktype / TopLevel.java+13 −0
| @@ -0,0 +1,13 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | +import java.util.Map; | |
| 5 | + | |
| 6 | +public class TopLevel { | |
| 7 | + private Map<String, Alternator> alternators; | |
| 8 | + | |
| 9 | + @JsonProperty("alternators") | |
| 10 | + public Map<String, Alternator> getAlternators() { return alternators; } | |
| 11 | + @JsonProperty("alternators") | |
| 12 | + public void setAlternators(Map<String, Alternator> value) { this.alternators = value; } | |
| 13 | +} |
Aschema-javadefault / src / main / java / io / quicktype / Alternator.java+18 −0
| @@ -0,0 +1,18 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | + | |
| 5 | +public class Alternator { | |
| 6 | + private String name; | |
| 7 | + private Double voltage; | |
| 8 | + | |
| 9 | + @JsonProperty("name") | |
| 10 | + public String getName() { return name; } | |
| 11 | + @JsonProperty("name") | |
| 12 | + public void setName(String value) { this.name = value; } | |
| 13 | + | |
| 14 | + @JsonProperty("voltage") | |
| 15 | + public Double getVoltage() { return voltage; } | |
| 16 | + @JsonProperty("voltage") | |
| 17 | + public void setVoltage(Double value) { this.voltage = value; } | |
| 18 | +} |
Aschema-javadefault / src / main / java / io / quicktype / Converter.java+101 −0
| @@ -0,0 +1,101 @@ | ||
| 1 | +// To use this code, add the following Maven dependency to your project: | |
| 2 | +// | |
| 3 | +// | |
| 4 | +// com.fasterxml.jackson.core : jackson-databind : 2.9.0 | |
| 5 | +// com.fasterxml.jackson.datatype : jackson-datatype-jsr310 : 2.9.0 | |
| 6 | +// | |
| 7 | +// Import this package: | |
| 8 | +// | |
| 9 | +// import io.quicktype.Converter; | |
| 10 | +// | |
| 11 | +// Then you can deserialize a JSON string with | |
| 12 | +// | |
| 13 | +// TopLevel data = Converter.fromJsonString(jsonString); | |
| 14 | + | |
| 15 | +package io.quicktype; | |
| 16 | + | |
| 17 | +import java.io.IOException; | |
| 18 | +import com.fasterxml.jackson.databind.*; | |
| 19 | +import com.fasterxml.jackson.databind.module.SimpleModule; | |
| 20 | +import com.fasterxml.jackson.core.JsonParser; | |
| 21 | +import com.fasterxml.jackson.core.JsonProcessingException; | |
| 22 | +import java.util.*; | |
| 23 | +import java.time.LocalDate; | |
| 24 | +import java.time.OffsetDateTime; | |
| 25 | +import java.time.OffsetTime; | |
| 26 | +import java.time.ZoneOffset; | |
| 27 | +import java.time.ZonedDateTime; | |
| 28 | +import java.time.format.DateTimeFormatter; | |
| 29 | +import java.time.format.DateTimeFormatterBuilder; | |
| 30 | +import java.time.temporal.ChronoField; | |
| 31 | + | |
| 32 | +public class Converter { | |
| 33 | + // Date-time helpers | |
| 34 | + | |
| 35 | + private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder() | |
| 36 | + .appendOptional(DateTimeFormatter.ISO_DATE_TIME) | |
| 37 | + .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME) | |
| 38 | + .appendOptional(DateTimeFormatter.ISO_INSTANT) | |
| 39 | + .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX")) | |
| 40 | + .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX")) | |
| 41 | + .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) | |
| 42 | + .toFormatter() | |
| 43 | + .withZone(ZoneOffset.UTC); | |
| 44 | + | |
| 45 | + public static OffsetDateTime parseDateTimeString(String str) { | |
| 46 | + return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime(); | |
| 47 | + } | |
| 48 | + | |
| 49 | + private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder() | |
| 50 | + .appendOptional(DateTimeFormatter.ISO_TIME) | |
| 51 | + .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME) | |
| 52 | + .parseDefaulting(ChronoField.YEAR, 2020) | |
| 53 | + .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1) | |
| 54 | + .parseDefaulting(ChronoField.DAY_OF_MONTH, 1) | |
| 55 | + .toFormatter() | |
| 56 | + .withZone(ZoneOffset.UTC); | |
| 57 | + | |
| 58 | + public static OffsetTime parseTimeString(String str) { | |
| 59 | + return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime(); | |
| 60 | + } | |
| 61 | + // Serialize/deserialize helpers | |
| 62 | + | |
| 63 | + public static TopLevel fromJsonString(String json) throws IOException { | |
| 64 | + return getObjectReader().readValue(json); | |
| 65 | + } | |
| 66 | + | |
| 67 | + public static String toJsonString(TopLevel obj) throws JsonProcessingException { | |
| 68 | + return getObjectWriter().writeValueAsString(obj); | |
| 69 | + } | |
| 70 | + | |
| 71 | + private static ObjectReader reader; | |
| 72 | + private static ObjectWriter writer; | |
| 73 | + | |
| 74 | + private static void instantiateMapper() { | |
| 75 | + ObjectMapper mapper = new ObjectMapper(); | |
| 76 | + mapper.findAndRegisterModules(); | |
| 77 | + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); | |
| 78 | + mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); | |
| 79 | + SimpleModule module = new SimpleModule(); | |
| 80 | + module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() { | |
| 81 | + @Override | |
| 82 | + public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { | |
| 83 | + String value = jsonParser.getText(); | |
| 84 | + return Converter.parseDateTimeString(value); | |
| 85 | + } | |
| 86 | + }); | |
| 87 | + mapper.registerModule(module); | |
| 88 | + reader = mapper.readerFor(TopLevel.class); | |
| 89 | + writer = mapper.writerFor(TopLevel.class); | |
| 90 | + } | |
| 91 | + | |
| 92 | + private static ObjectReader getObjectReader() { | |
| 93 | + if (reader == null) instantiateMapper(); | |
| 94 | + return reader; | |
| 95 | + } | |
| 96 | + | |
| 97 | + private static ObjectWriter getObjectWriter() { | |
| 98 | + if (writer == null) instantiateMapper(); | |
| 99 | + return writer; | |
| 100 | + } | |
| 101 | +} |
Aschema-javadefault / src / main / java / io / quicktype / TopLevel.java+13 −0
| @@ -0,0 +1,13 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | +import java.util.Map; | |
| 5 | + | |
| 6 | +public class TopLevel { | |
| 7 | + private Map<String, Alternator> alternators; | |
| 8 | + | |
| 9 | + @JsonProperty("alternators") | |
| 10 | + public Map<String, Alternator> getAlternators() { return alternators; } | |
| 11 | + @JsonProperty("alternators") | |
| 12 | + public void setAlternators(Map<String, Alternator> value) { this.alternators = value; } | |
| 13 | +} |
Aschema-javascriptdefault / TopLevel.js+186 −0
| @@ -0,0 +1,186 @@ | ||
| 1 | +// To parse this data: | |
| 2 | +// | |
| 3 | +// const Convert = require("./TopLevel"); | |
| 4 | +// | |
| 5 | +// const topLevel = Convert.toTopLevel(json); | |
| 6 | +// | |
| 7 | +// These functions will throw an error if the JSON doesn't | |
| 8 | +// match the expected interface, even if the JSON is valid. | |
| 9 | + | |
| 10 | +// Converts JSON strings to/from your types | |
| 11 | +// and asserts the results of JSON.parse at runtime | |
| 12 | +function toTopLevel(json) { | |
| 13 | + return cast(JSON.parse(json), r("TopLevel")); | |
| 14 | +} | |
| 15 | + | |
| 16 | +function topLevelToJson(value) { | |
| 17 | + return JSON.stringify(uncast(value, r("TopLevel")), null, 2); | |
| 18 | +} | |
| 19 | + | |
| 20 | +function invalidValue(typ, val, key, parent = '') { | |
| 21 | + const prettyTyp = prettyTypeName(typ); | |
| 22 | + const parentText = parent ? ` on ${parent}` : ''; | |
| 23 | + const keyText = key ? ` for key "${key}"` : ''; | |
| 24 | + throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`); | |
| 25 | +} | |
| 26 | + | |
| 27 | +function prettyTypeName(typ) { | |
| 28 | + if (Array.isArray(typ)) { | |
| 29 | + if (typ.length === 2 && typ[0] === undefined) { | |
| 30 | + return `an optional ${prettyTypeName(typ[1])}`; | |
| 31 | + } else { | |
| 32 | + return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`; | |
| 33 | + } | |
| 34 | + } else if (typeof typ === "object" && typ.literal !== undefined) { | |
| 35 | + return typ.literal; | |
| 36 | + } else { | |
| 37 | + return typeof typ; | |
| 38 | + } | |
| 39 | +} | |
| 40 | + | |
| 41 | +function jsonToJSProps(typ) { | |
| 42 | + if (typ.jsonToJS === undefined) { | |
| 43 | + const map = {}; | |
| 44 | + typ.props.forEach((p) => map[p.json] = { key: p.js, typ: p.typ }); | |
| 45 | + typ.jsonToJS = map; | |
| 46 | + } | |
| 47 | + return typ.jsonToJS; | |
| 48 | +} | |
| 49 | + | |
| 50 | +function jsToJSONProps(typ) { | |
| 51 | + if (typ.jsToJSON === undefined) { | |
| 52 | + const map = {}; | |
| 53 | + typ.props.forEach((p) => map[p.js] = { key: p.json, typ: p.typ }); | |
| 54 | + typ.jsToJSON = map; | |
| 55 | + } | |
| 56 | + return typ.jsToJSON; | |
| 57 | +} | |
| 58 | + | |
| 59 | +function transform(val, typ, getProps, key = '', parent = '') { | |
| 60 | + function transformPrimitive(typ, val) { | |
| 61 | + if (typeof typ === typeof val) return val; | |
| 62 | + return invalidValue(typ, val, key, parent); | |
| 63 | + } | |
| 64 | + | |
| 65 | + function transformUnion(typs, val) { | |
| 66 | + // val must validate against one typ in typs | |
| 67 | + const l = typs.length; | |
| 68 | + for (let i = 0; i < l; i++) { | |
| 69 | + const typ = typs[i]; | |
| 70 | + try { | |
| 71 | + return transform(val, typ, getProps); | |
| 72 | + } catch (_) {} | |
| 73 | + } | |
| 74 | + return invalidValue(typs, val, key, parent); | |
| 75 | + } | |
| 76 | + | |
| 77 | + function transformEnum(cases, val) { | |
| 78 | + if (cases.indexOf(val) !== -1) return val; | |
| 79 | + return invalidValue(cases.map(a => { return l(a); }), val, key, parent); | |
| 80 | + } | |
| 81 | + | |
| 82 | + function transformArray(typ, val) { | |
| 83 | + // val must be an array with no invalid elements | |
| 84 | + if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent); | |
| 85 | + return val.map(el => transform(el, typ, getProps)); | |
| 86 | + } | |
| 87 | + | |
| 88 | + function transformDate(val) { | |
| 89 | + if (val === null) { | |
| 90 | + return null; | |
| 91 | + } | |
| 92 | + const d = new Date(val); | |
| 93 | + if (isNaN(d.valueOf())) { | |
| 94 | + return invalidValue(l("Date"), val, key, parent); | |
| 95 | + } | |
| 96 | + return d; | |
| 97 | + } | |
| 98 | + | |
| 99 | + function transformObject(props, additional, val) { | |
| 100 | + if (val === null || typeof val !== "object" || Array.isArray(val)) { | |
| 101 | + return invalidValue(l(ref || "object"), val, key, parent); | |
| 102 | + } | |
| 103 | + const result = {}; | |
| 104 | + Object.getOwnPropertyNames(props).forEach(key => { | |
| 105 | + const prop = props[key]; | |
| 106 | + const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined; | |
| 107 | + result[prop.key] = transform(v, prop.typ, getProps, key, ref); | |
| 108 | + }); | |
| 109 | + Object.getOwnPropertyNames(val).forEach(key => { | |
| 110 | + if (!Object.prototype.hasOwnProperty.call(props, key)) { | |
| 111 | + result[key] = transform(val[key], additional, getProps, key, ref); | |
| 112 | + } | |
| 113 | + }); | |
| 114 | + return result; | |
| 115 | + } | |
| 116 | + | |
| 117 | + if (typ === "any") return val; | |
| 118 | + if (typ === null) { | |
| 119 | + if (val === null) return val; | |
| 120 | + return invalidValue(typ, val, key, parent); | |
| 121 | + } | |
| 122 | + if (typ === false) return invalidValue(typ, val, key, parent); | |
| 123 | + let ref = undefined; | |
| 124 | + while (typeof typ === "object" && typ.ref !== undefined) { | |
| 125 | + ref = typ.ref; | |
| 126 | + typ = typeMap[typ.ref]; | |
| 127 | + } | |
| 128 | + if (Array.isArray(typ)) return transformEnum(typ, val); | |
| 129 | + if (typeof typ === "object") { | |
| 130 | + return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val) | |
| 131 | + : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val) | |
| 132 | + : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val) | |
| 133 | + : invalidValue(typ, val, key, parent); | |
| 134 | + } | |
| 135 | + // Numbers can be parsed by Date but shouldn't be. | |
| 136 | + if (typ === Date && typeof val !== "number") return transformDate(val); | |
| 137 | + return transformPrimitive(typ, val); | |
| 138 | +} | |
| 139 | + | |
| 140 | +function cast(val, typ) { | |
| 141 | + return transform(val, typ, jsonToJSProps); | |
| 142 | +} | |
| 143 | + | |
| 144 | +function uncast(val, typ) { | |
| 145 | + return transform(val, typ, jsToJSONProps); | |
| 146 | +} | |
| 147 | + | |
| 148 | +function l(typ) { | |
| 149 | + return { literal: typ }; | |
| 150 | +} | |
| 151 | + | |
| 152 | +function a(typ) { | |
| 153 | + return { arrayItems: typ }; | |
| 154 | +} | |
| 155 | + | |
| 156 | +function u(...typs) { | |
| 157 | + return { unionMembers: typs }; | |
| 158 | +} | |
| 159 | + | |
| 160 | +function o(props, additional) { | |
| 161 | + return { props, additional }; | |
| 162 | +} | |
| 163 | + | |
| 164 | +function m(additional) { | |
| 165 | + const props = []; | |
| 166 | + return { props, additional }; | |
| 167 | +} | |
| 168 | + | |
| 169 | +function r(name) { | |
| 170 | + return { ref: name }; | |
| 171 | +} | |
| 172 | + | |
| 173 | +const typeMap = { | |
| 174 | + "TopLevel": o([ | |
| 175 | + { json: "alternators", js: "alternators", typ: u(undefined, m(r("Alternator"))) }, | |
| 176 | + ], "any"), | |
| 177 | + "Alternator": o([ | |
| 178 | + { json: "name", js: "name", typ: u(undefined, "") }, | |
| 179 | + { json: "voltage", js: "voltage", typ: u(undefined, 3.14) }, | |
| 180 | + ], "any"), | |
| 181 | +}; | |
| 182 | + | |
| 183 | +module.exports = { | |
| 184 | + "topLevelToJson": topLevelToJson, | |
| 185 | + "toTopLevel": toTopLevel, | |
| 186 | +}; |
Aschema-kotlinxdefault / TopLevel.kt+22 −0
| @@ -0,0 +1,22 @@ | ||
| 1 | +// To parse the JSON, install kotlin's serialization plugin and do: | |
| 2 | +// | |
| 3 | +// val json = Json { allowStructuredMapKeys = true } | |
| 4 | +// val topLevel = json.parse(TopLevel.serializer(), jsonString) | |
| 5 | + | |
| 6 | +package quicktype | |
| 7 | + | |
| 8 | +import kotlinx.serialization.* | |
| 9 | +import kotlinx.serialization.json.* | |
| 10 | +import kotlinx.serialization.descriptors.* | |
| 11 | +import kotlinx.serialization.encoding.* | |
| 12 | + | |
| 13 | +@Serializable | |
| 14 | +data class TopLevel ( | |
| 15 | + val alternators: Map<String, Alternator>? = null | |
| 16 | +) | |
| 17 | + | |
| 18 | +@Serializable | |
| 19 | +data class Alternator ( | |
| 20 | + val name: String? = null, | |
| 21 | + val voltage: Double? = null | |
| 22 | +) |
Aschema-phpdefault / TopLevel.php+297 −0
| @@ -0,0 +1,297 @@ | ||
| 1 | +<?php | |
| 2 | +declare(strict_types=1); | |
| 3 | + | |
| 4 | +// This is an autogenerated file:TopLevel | |
| 5 | + | |
| 6 | +class TopLevel { | |
| 7 | + private ?stdClass $alternators; // json:alternators Optional | |
| 8 | + | |
| 9 | + /** | |
| 10 | + * @param stdClass|null $alternators | |
| 11 | + */ | |
| 12 | + public function __construct(?stdClass $alternators) { | |
| 13 | + $this->alternators = $alternators; | |
| 14 | + } | |
| 15 | + | |
| 16 | + /** | |
| 17 | + * @param ?stdClass $value | |
| 18 | + * @throws Exception | |
| 19 | + * @return ?stdClass | |
| 20 | + */ | |
| 21 | + public static function fromAlternators(?stdClass $value): ?stdClass { | |
| 22 | + if (!is_null($value)) { | |
| 23 | + $out = new stdClass(); | |
| 24 | + foreach ($value as $k => $v) { | |
| 25 | + $out->$k = Alternator::from($v); /*class*/ | |
| 26 | + } | |
| 27 | + return $out; | |
| 28 | + } else { | |
| 29 | + return null; | |
| 30 | + } | |
| 31 | + } | |
| 32 | + | |
| 33 | + /** | |
| 34 | + * @throws Exception | |
| 35 | + * @return ?stdClass | |
| 36 | + */ | |
| 37 | + public function toAlternators(): ?stdClass { | |
| 38 | + if (TopLevel::validateAlternators($this->alternators)) { | |
| 39 | + if (!is_null($this->alternators)) { | |
| 40 | + $out = new stdClass(); | |
| 41 | + foreach ($this->alternators as $k => $v) { | |
| 42 | + $out->$k = $v->to(); /*class*/ | |
| 43 | + } | |
| 44 | + return $out; | |
| 45 | + } else { | |
| 46 | + return null; | |
| 47 | + } | |
| 48 | + } | |
| 49 | + throw new Exception('never get to this TopLevel::alternators'); | |
| 50 | + } | |
| 51 | + | |
| 52 | + /** | |
| 53 | + * @param stdClass|null | |
| 54 | + * @return bool | |
| 55 | + * @throws Exception | |
| 56 | + */ | |
| 57 | + public static function validateAlternators(?stdClass $value): bool { | |
| 58 | + if (!is_null($value)) { | |
| 59 | + foreach ($value as $k => $v) { | |
| 60 | + $v->validate(); | |
| 61 | + } | |
| 62 | + } | |
| 63 | + return true; | |
| 64 | + } | |
| 65 | + | |
| 66 | + /** | |
| 67 | + * @throws Exception | |
| 68 | + * @return ?stdClass | |
| 69 | + */ | |
| 70 | + public function getAlternators(): ?stdClass { | |
| 71 | + if (TopLevel::validateAlternators($this->alternators)) { | |
| 72 | + return $this->alternators; | |
| 73 | + } | |
| 74 | + throw new Exception('never get to getAlternators TopLevel::alternators'); | |
| 75 | + } | |
| 76 | + | |
| 77 | + /** | |
| 78 | + * @return ?stdClass | |
| 79 | + */ | |
| 80 | + public static function sampleAlternators(): ?stdClass { | |
| 81 | + return (function () { | |
| 82 | + $out = new stdClass(); | |
| 83 | + $out->{'TopLevel'} = Alternator::sample(); /*31:alternators*/ | |
| 84 | + return $out; | |
| 85 | + })(); /* 31:alternators*/ | |
| 86 | + } | |
| 87 | + | |
| 88 | + /** | |
| 89 | + * @throws Exception | |
| 90 | + * @return bool | |
| 91 | + */ | |
| 92 | + public function validate(): bool { | |
| 93 | + return TopLevel::validateAlternators($this->alternators); | |
| 94 | + } | |
| 95 | + | |
| 96 | + /** | |
| 97 | + * @return stdClass | |
| 98 | + * @throws Exception | |
| 99 | + */ | |
| 100 | + public function to(): stdClass { | |
| 101 | + $out = new stdClass(); | |
| 102 | + $out->{'alternators'} = $this->toAlternators(); | |
| 103 | + return $out; | |
| 104 | + } | |
| 105 | + | |
| 106 | + /** | |
| 107 | + * @param stdClass $obj | |
| 108 | + * @return TopLevel | |
| 109 | + * @throws Exception | |
| 110 | + */ | |
| 111 | + public static function from(stdClass $obj): TopLevel { | |
| 112 | + return new TopLevel( | |
| 113 | + TopLevel::fromAlternators($obj->{'alternators'}) | |
| 114 | + ); | |
| 115 | + } | |
| 116 | + | |
| 117 | + /** | |
| 118 | + * @return TopLevel | |
| 119 | + */ | |
| 120 | + public static function sample(): TopLevel { | |
| 121 | + return new TopLevel( | |
| 122 | + TopLevel::sampleAlternators() | |
| 123 | + ); | |
| 124 | + } | |
| 125 | +} | |
| 126 | + | |
| 127 | +// This is an autogenerated file:Alternator | |
| 128 | + | |
| 129 | +class Alternator { | |
| 130 | + private ?string $name; // json:name Optional | |
| 131 | + private ?float $voltage; // json:voltage Optional | |
| 132 | + | |
| 133 | + /** | |
| 134 | + * @param string|null $name | |
| 135 | + * @param float|null $voltage | |
| 136 | + */ | |
| 137 | + public function __construct(?string $name, ?float $voltage) { | |
| 138 | + $this->name = $name; | |
| 139 | + $this->voltage = $voltage; | |
| 140 | + } | |
| 141 | + | |
| 142 | + /** | |
| 143 | + * @param ?string $value | |
| 144 | + * @throws Exception | |
| 145 | + * @return ?string | |
| 146 | + */ | |
| 147 | + public static function fromName(?string $value): ?string { | |
| 148 | + if (!is_null($value)) { | |
| 149 | + return $value; /*string*/ | |
| 150 | + } else { | |
| 151 | + return null; | |
| 152 | + } | |
| 153 | + } | |
| 154 | + | |
| 155 | + /** | |
| 156 | + * @throws Exception | |
| 157 | + * @return ?string | |
| 158 | + */ | |
| 159 | + public function toName(): ?string { | |
| 160 | + if (Alternator::validateName($this->name)) { | |
| 161 | + if (!is_null($this->name)) { | |
| 162 | + return $this->name; /*string*/ | |
| 163 | + } else { | |
| 164 | + return null; | |
| 165 | + } | |
| 166 | + } | |
| 167 | + throw new Exception('never get to this Alternator::name'); | |
| 168 | + } | |
| 169 | + | |
| 170 | + /** | |
| 171 | + * @param string|null | |
| 172 | + * @return bool | |
| 173 | + * @throws Exception | |
| 174 | + */ | |
| 175 | + public static function validateName(?string $value): bool { | |
| 176 | + if (!is_null($value)) { | |
| 177 | + } | |
| 178 | + return true; | |
| 179 | + } | |
| 180 | + | |
| 181 | + /** | |
| 182 | + * @throws Exception | |
| 183 | + * @return ?string | |
| 184 | + */ | |
| 185 | + public function getName(): ?string { | |
| 186 | + if (Alternator::validateName($this->name)) { | |
| 187 | + return $this->name; | |
| 188 | + } | |
| 189 | + throw new Exception('never get to getName Alternator::name'); | |
| 190 | + } | |
| 191 | + | |
| 192 | + /** | |
| 193 | + * @return ?string | |
| 194 | + */ | |
| 195 | + public static function sampleName(): ?string { | |
| 196 | + return 'Alternator::name::31'; /*31:name*/ | |
| 197 | + } | |
| 198 | + | |
| 199 | + /** | |
| 200 | + * @param ?float $value | |
| 201 | + * @throws Exception | |
| 202 | + * @return ?float | |
| 203 | + */ | |
| 204 | + public static function fromVoltage(?float $value): ?float { | |
| 205 | + if (!is_null($value)) { | |
| 206 | + return $value; /*float*/ | |
| 207 | + } else { | |
| 208 | + return null; | |
| 209 | + } | |
| 210 | + } | |
| 211 | + | |
| 212 | + /** | |
| 213 | + * @throws Exception | |
| 214 | + * @return ?float | |
| 215 | + */ | |
| 216 | + public function toVoltage(): ?float { | |
| 217 | + if (Alternator::validateVoltage($this->voltage)) { | |
| 218 | + if (!is_null($this->voltage)) { | |
| 219 | + return $this->voltage; /*float*/ | |
| 220 | + } else { | |
| 221 | + return null; | |
| 222 | + } | |
| 223 | + } | |
| 224 | + throw new Exception('never get to this Alternator::voltage'); | |
| 225 | + } | |
| 226 | + | |
| 227 | + /** | |
| 228 | + * @param float|null | |
| 229 | + * @return bool | |
| 230 | + * @throws Exception | |
| 231 | + */ | |
| 232 | + public static function validateVoltage(?float $value): bool { | |
| 233 | + if (!is_null($value)) { | |
| 234 | + } | |
| 235 | + return true; | |
| 236 | + } | |
| 237 | + | |
| 238 | + /** | |
| 239 | + * @throws Exception | |
| 240 | + * @return ?float | |
| 241 | + */ | |
| 242 | + public function getVoltage(): ?float { | |
| 243 | + if (Alternator::validateVoltage($this->voltage)) { | |
| 244 | + return $this->voltage; | |
| 245 | + } | |
| 246 | + throw new Exception('never get to getVoltage Alternator::voltage'); | |
| 247 | + } | |
| 248 | + | |
| 249 | + /** | |
| 250 | + * @return ?float | |
| 251 | + */ | |
| 252 | + public static function sampleVoltage(): ?float { | |
| 253 | + return 32.032; /*32:voltage*/ | |
| 254 | + } | |
| 255 | + | |
| 256 | + /** | |
| 257 | + * @throws Exception | |
| 258 | + * @return bool | |
| 259 | + */ | |
| 260 | + public function validate(): bool { | |
| 261 | + return Alternator::validateName($this->name) | |
| 262 | + || Alternator::validateVoltage($this->voltage); | |
| 263 | + } | |
| 264 | + | |
| 265 | + /** | |
| 266 | + * @return stdClass | |
| 267 | + * @throws Exception | |
| 268 | + */ | |
| 269 | + public function to(): stdClass { | |
| 270 | + $out = new stdClass(); | |
| 271 | + $out->{'name'} = $this->toName(); | |
| 272 | + $out->{'voltage'} = $this->toVoltage(); | |
| 273 | + return $out; | |
| 274 | + } | |
| 275 | + | |
| 276 | + /** | |
| 277 | + * @param stdClass $obj | |
| 278 | + * @return Alternator | |
| 279 | + * @throws Exception | |
| 280 | + */ | |
| 281 | + public static function from(stdClass $obj): Alternator { | |
| 282 | + return new Alternator( | |
| 283 | + Alternator::fromName($obj->{'name'}) | |
| 284 | + ,Alternator::fromVoltage($obj->{'voltage'}) | |
| 285 | + ); | |
| 286 | + } | |
| 287 | + | |
| 288 | + /** | |
| 289 | + * @return Alternator | |
| 290 | + */ | |
| 291 | + public static function sample(): Alternator { | |
| 292 | + return new Alternator( | |
| 293 | + Alternator::sampleName() | |
| 294 | + ,Alternator::sampleVoltage() | |
| 295 | + ); | |
| 296 | + } | |
| 297 | +} |
Aschema-pythondefault / quicktype.py+90 −0
| @@ -0,0 +1,90 @@ | ||
| 1 | +from dataclasses import dataclass | |
| 2 | +from typing import Any, TypeVar, Callable, Type, cast | |
| 3 | + | |
| 4 | + | |
| 5 | +T = TypeVar("T") | |
| 6 | + | |
| 7 | + | |
| 8 | +def from_str(x: Any) -> str: | |
| 9 | + assert isinstance(x, str) | |
| 10 | + return x | |
| 11 | + | |
| 12 | + | |
| 13 | +def from_none(x: Any) -> Any: | |
| 14 | + assert x is None | |
| 15 | + return x | |
| 16 | + | |
| 17 | + | |
| 18 | +def from_union(fs, x): | |
| 19 | + for f in fs: | |
| 20 | + try: | |
| 21 | + return f(x) | |
| 22 | + except: | |
| 23 | + pass | |
| 24 | + assert False | |
| 25 | + | |
| 26 | + | |
| 27 | +def from_float(x: Any) -> float: | |
| 28 | + assert isinstance(x, (float, int)) and not isinstance(x, bool) | |
| 29 | + return float(x) | |
| 30 | + | |
| 31 | + | |
| 32 | +def to_float(x: Any) -> float: | |
| 33 | + assert isinstance(x, (int, float)) | |
| 34 | + return x | |
| 35 | + | |
| 36 | + | |
| 37 | +def from_dict(f: Callable[[Any], T], x: Any) -> dict[str, T]: | |
| 38 | + assert isinstance(x, dict) | |
| 39 | + return { k: f(v) for (k, v) in x.items() } | |
| 40 | + | |
| 41 | + | |
| 42 | +def to_class(c: Type[T], x: Any) -> dict: | |
| 43 | + assert isinstance(x, c) | |
| 44 | + return cast(Any, x).to_dict() | |
| 45 | + | |
| 46 | + | |
| 47 | +@dataclass | |
| 48 | +class Alternator: | |
| 49 | + name: str | None = None | |
| 50 | + voltage: float | None = None | |
| 51 | + | |
| 52 | + @staticmethod | |
| 53 | + def from_dict(obj: Any) -> 'Alternator': | |
| 54 | + assert isinstance(obj, dict) | |
| 55 | + name = from_union([from_str, from_none], obj.get("name")) | |
| 56 | + voltage = from_union([from_float, from_none], obj.get("voltage")) | |
| 57 | + return Alternator(name, voltage) | |
| 58 | + | |
| 59 | + def to_dict(self) -> dict: | |
| 60 | + result: dict = {} | |
| 61 | + if self.name is not None: | |
| 62 | + result["name"] = from_union([from_str, from_none], self.name) | |
| 63 | + if self.voltage is not None: | |
| 64 | + result["voltage"] = from_union([to_float, from_none], self.voltage) | |
| 65 | + return result | |
| 66 | + | |
| 67 | + | |
| 68 | +@dataclass | |
| 69 | +class TopLevel: | |
| 70 | + alternators: dict[str, Alternator] | None = None | |
| 71 | + | |
| 72 | + @staticmethod | |
| 73 | + def from_dict(obj: Any) -> 'TopLevel': | |
| 74 | + assert isinstance(obj, dict) | |
| 75 | + alternators = from_union([lambda x: from_dict(Alternator.from_dict, x), from_none], obj.get("alternators")) | |
| 76 | + return TopLevel(alternators) | |
| 77 | + | |
| 78 | + def to_dict(self) -> dict: | |
| 79 | + result: dict = {} | |
| 80 | + if self.alternators is not None: | |
| 81 | + result["alternators"] = from_union([lambda x: from_dict(lambda x: to_class(Alternator, x), x), from_none], self.alternators) | |
| 82 | + return result | |
| 83 | + | |
| 84 | + | |
| 85 | +def top_level_from_dict(s: Any) -> TopLevel: | |
| 86 | + return TopLevel.from_dict(s) | |
| 87 | + | |
| 88 | + | |
| 89 | +def top_level_to_dict(x: TopLevel) -> Any: | |
| 90 | + return to_class(TopLevel, x) |
Aschema-rubydefault / TopLevel.rb+74 −0
| @@ -0,0 +1,74 @@ | ||
| 1 | +# This code may look unusually verbose for Ruby (and it is), but | |
| 2 | +# it performs some subtle and complex validation of JSON data. | |
| 3 | +# | |
| 4 | +# To parse this JSON, add 'dry-struct' and 'dry-types' gems, then do: | |
| 5 | +# | |
| 6 | +# top_level = TopLevel.from_json! "{…}" | |
| 7 | +# puts top_level.alternators&["…"].alternator_name | |
| 8 | +# | |
| 9 | +# If from_json! succeeds, the value returned matches the schema. | |
| 10 | + | |
| 11 | +require 'json' | |
| 12 | +require 'dry-types' | |
| 13 | +require 'dry-struct' | |
| 14 | + | |
| 15 | +module Types | |
| 16 | + include Dry.Types(default: :nominal) | |
| 17 | + | |
| 18 | + Hash = Strict::Hash | |
| 19 | + String = Strict::String | |
| 20 | + Double = Strict::Float | Strict::Integer | |
| 21 | +end | |
| 22 | + | |
| 23 | +class Alternator < Dry::Struct | |
| 24 | + attribute :alternator_name, Types::String.optional | |
| 25 | + attribute :voltage, Types::Double.optional | |
| 26 | + | |
| 27 | + def self.from_dynamic!(d) | |
| 28 | + d = Types::Hash[d] | |
| 29 | + new( | |
| 30 | + alternator_name: d["name"], | |
| 31 | + voltage: d["voltage"], | |
| 32 | + ) | |
| 33 | + end | |
| 34 | + | |
| 35 | + def self.from_json!(json) | |
| 36 | + from_dynamic!(JSON.parse(json)) | |
| 37 | + end | |
| 38 | + | |
| 39 | + def to_dynamic | |
| 40 | + { | |
| 41 | + "name" => alternator_name, | |
| 42 | + "voltage" => voltage, | |
| 43 | + } | |
| 44 | + end | |
| 45 | + | |
| 46 | + def to_json(options = nil) | |
| 47 | + JSON.generate(to_dynamic, options) | |
| 48 | + end | |
| 49 | +end | |
| 50 | + | |
| 51 | +class TopLevel < Dry::Struct | |
| 52 | + attribute :alternators, Types::Hash.meta(of: Alternator).optional | |
| 53 | + | |
| 54 | + def self.from_dynamic!(d) | |
| 55 | + d = Types::Hash[d] | |
| 56 | + new( | |
| 57 | + alternators: Types::Hash.optional[d["alternators"]]&.map { |k, v| [k, Alternator.from_dynamic!(v)] }&.to_h, | |
| 58 | + ) | |
| 59 | + end | |
| 60 | + | |
| 61 | + def self.from_json!(json) | |
| 62 | + from_dynamic!(JSON.parse(json)) | |
| 63 | + end | |
| 64 | + | |
| 65 | + def to_dynamic | |
| 66 | + { | |
| 67 | + "alternators" => alternators&.map { |k, v| [k, v.to_dynamic] }.to_h, | |
| 68 | + } | |
| 69 | + end | |
| 70 | + | |
| 71 | + def to_json(options = nil) | |
| 72 | + JSON.generate(to_dynamic, options) | |
| 73 | + end | |
| 74 | +end |
Aschema-rustdefault / module_under_test.rs+27 −0
| @@ -0,0 +1,27 @@ | ||
| 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 | +use std::collections::HashMap; | |
| 16 | + | |
| 17 | +#[derive(Debug, Clone, Serialize, Deserialize)] | |
| 18 | +pub struct TopLevel { | |
| 19 | + pub alternators: Option<HashMap<String, Alternator>>, | |
| 20 | +} | |
| 21 | + | |
| 22 | +#[derive(Debug, Clone, Serialize, Deserialize)] | |
| 23 | +pub struct Alternator { | |
| 24 | + pub name: Option<String>, | |
| 25 | + | |
| 26 | + pub voltage: Option<f64>, | |
| 27 | +} |
Aschema-scala3-upickledefault / TopLevel.scala+75 −0
| @@ -0,0 +1,75 @@ | ||
| 1 | +package quicktype | |
| 2 | + | |
| 3 | +// Custom pickler so that missing keys and JSON nulls both read as None, | |
| 4 | +// and None is left out when writing (upickle's default for Option is a | |
| 5 | +// JSON array). | |
| 6 | +object OptionPickler extends upickle.AttributeTagged: | |
| 7 | + import upickle.default.Writer | |
| 8 | + import upickle.default.Reader | |
| 9 | + override implicit def OptionWriter[T: Writer]: Writer[Option[T]] = | |
| 10 | + implicitly[Writer[T]].comap[Option[T]] { | |
| 11 | + case None => null.asInstanceOf[T] | |
| 12 | + case Some(x) => x | |
| 13 | + } | |
| 14 | + | |
| 15 | + override implicit def OptionReader[T: Reader]: Reader[Option[T]] = { | |
| 16 | + new Reader.Delegate[Any, Option[T]](implicitly[Reader[T]].map(Some(_))){ | |
| 17 | + override def visitNull(index: Int) = None | |
| 18 | + } | |
| 19 | + } | |
| 20 | +end OptionPickler | |
| 21 | + | |
| 22 | +// If a union has a null in, then we'll need this too... | |
| 23 | +type NullValue = None.type | |
| 24 | +given OptionPickler.ReadWriter[NullValue] = OptionPickler.readwriter[ujson.Value].bimap[NullValue]( | |
| 25 | + _ => ujson.Null, | |
| 26 | + json => if json.isNull then None else throw new upickle.core.Abort("not null") | |
| 27 | +) | |
| 28 | + | |
| 29 | +object JsonExt: | |
| 30 | + val valueReader = OptionPickler.readwriter[ujson.Value] | |
| 31 | + | |
| 32 | + // upickle's built-in primitive readers are lenient -- the numeric and | |
| 33 | + // boolean readers accept strings, and the string reader accepts | |
| 34 | + // numbers and booleans -- so untagged unions need strict readers to | |
| 35 | + // pick the right member. | |
| 36 | + val strictString: OptionPickler.Reader[String] = valueReader.map { | |
| 37 | + case ujson.Str(s) => s | |
| 38 | + case json => throw new upickle.core.Abort("expected string, got " + json) | |
| 39 | + } | |
| 40 | + val strictLong: OptionPickler.Reader[Long] = valueReader.map { | |
| 41 | + case ujson.Num(n) if n.isWhole => n.toLong | |
| 42 | + case json => throw new upickle.core.Abort("expected integer, got " + json) | |
| 43 | + } | |
| 44 | + val strictDouble: OptionPickler.Reader[Double] = valueReader.map { | |
| 45 | + case ujson.Num(n) => n | |
| 46 | + case json => throw new upickle.core.Abort("expected number, got " + json) | |
| 47 | + } | |
| 48 | + val strictBoolean: OptionPickler.Reader[Boolean] = valueReader.map { | |
| 49 | + case ujson.Bool(b) => b | |
| 50 | + case json => throw new upickle.core.Abort("expected boolean, got " + json) | |
| 51 | + } | |
| 52 | + | |
| 53 | + def badMerge[T](r1: => OptionPickler.Reader[?], rest: OptionPickler.Reader[?]*): OptionPickler.Reader[T] = valueReader.map { json => | |
| 54 | + var t: T | Null = null | |
| 55 | + val stack = Vector.newBuilder[Throwable] | |
| 56 | + (r1 +: rest).foreach { reader => | |
| 57 | + if t == null then | |
| 58 | + try | |
| 59 | + t = OptionPickler.read[T](json, trace = true)(using reader.asInstanceOf[OptionPickler.Reader[T]]) | |
| 60 | + catch | |
| 61 | + case exc => stack += exc | |
| 62 | + } | |
| 63 | + if t != null then t.nn else throw new Exception(json.toString(), stack.result().headOption.getOrElse(null)) | |
| 64 | + } | |
| 65 | +end JsonExt | |
| 66 | + | |
| 67 | + | |
| 68 | +case class TopLevel ( | |
| 69 | + val alternators : Option[Map[String, Alternator]] = None | |
| 70 | +) derives OptionPickler.ReadWriter | |
| 71 | + | |
| 72 | +case class Alternator ( | |
| 73 | + val name : Option[String] = None, | |
| 74 | + val voltage : Option[Double] = None | |
| 75 | +) derives OptionPickler.ReadWriter |
Aschema-scala3default / TopLevel.scala+17 −0
| @@ -0,0 +1,17 @@ | ||
| 1 | +package quicktype | |
| 2 | + | |
| 3 | +import io.circe.syntax._ | |
| 4 | +import io.circe._ | |
| 5 | +import cats.syntax.functor._ | |
| 6 | + | |
| 7 | +// If a union has a null in, then we'll need this too... | |
| 8 | +type NullValue = None.type | |
| 9 | + | |
| 10 | +case class TopLevel ( | |
| 11 | + val alternators : Option[Map[String, Alternator]] = None | |
| 12 | +) derives Encoder.AsObject, Decoder | |
| 13 | + | |
| 14 | +case class Alternator ( | |
| 15 | + val name : Option[String] = None, | |
| 16 | + val voltage : Option[Double] = None | |
| 17 | +) derives Encoder.AsObject, Decoder |
Aschema-schemadefault / TopLevel.schema+34 −0
| @@ -0,0 +1,34 @@ | ||
| 1 | +{ | |
| 2 | + "$schema": "http://json-schema.org/draft-06/schema#", | |
| 3 | + "$ref": "#/definitions/TopLevel", | |
| 4 | + "definitions": { | |
| 5 | + "TopLevel": { | |
| 6 | + "type": "object", | |
| 7 | + "additionalProperties": {}, | |
| 8 | + "properties": { | |
| 9 | + "alternators": { | |
| 10 | + "type": "object", | |
| 11 | + "additionalProperties": { | |
| 12 | + "$ref": "#/definitions/Alternator" | |
| 13 | + } | |
| 14 | + } | |
| 15 | + }, | |
| 16 | + "required": [], | |
| 17 | + "title": "TopLevel" | |
| 18 | + }, | |
| 19 | + "Alternator": { | |
| 20 | + "type": "object", | |
| 21 | + "additionalProperties": {}, | |
| 22 | + "properties": { | |
| 23 | + "name": { | |
| 24 | + "type": "string" | |
| 25 | + }, | |
| 26 | + "voltage": { | |
| 27 | + "type": "number" | |
| 28 | + } | |
| 29 | + }, | |
| 30 | + "required": [], | |
| 31 | + "title": "Alternator" | |
| 32 | + } | |
| 33 | + } | |
| 34 | +} |
Aschema-typescriptdefault / TopLevel.ts+194 −0
| @@ -0,0 +1,194 @@ | ||
| 1 | +// To parse this data: | |
| 2 | +// | |
| 3 | +// import { Convert, TopLevel } from "./TopLevel"; | |
| 4 | +// | |
| 5 | +// const topLevel = Convert.toTopLevel(json); | |
| 6 | +// | |
| 7 | +// These functions will throw an error if the JSON doesn't | |
| 8 | +// match the expected interface, even if the JSON is valid. | |
| 9 | + | |
| 10 | +export interface TopLevel { | |
| 11 | + alternators?: { [key: string]: Alternator }; | |
| 12 | + [property: string]: unknown; | |
| 13 | +} | |
| 14 | + | |
| 15 | +export interface Alternator { | |
| 16 | + name?: string; | |
| 17 | + voltage?: number; | |
| 18 | + [property: string]: unknown; | |
| 19 | +} | |
| 20 | + | |
| 21 | +// Converts JSON strings to/from your types | |
| 22 | +// and asserts the results of JSON.parse at runtime | |
| 23 | +export class Convert { | |
| 24 | + public static toTopLevel(json: string): TopLevel { | |
| 25 | + return cast(JSON.parse(json), r("TopLevel")); | |
| 26 | + } | |
| 27 | + | |
| 28 | + public static topLevelToJson(value: TopLevel): string { | |
| 29 | + return JSON.stringify(uncast(value, r("TopLevel")), null, 2); | |
| 30 | + } | |
| 31 | +} | |
| 32 | + | |
| 33 | +function invalidValue(typ: any, val: any, key: any, parent: any = ''): never { | |
| 34 | + const prettyTyp = prettyTypeName(typ); | |
| 35 | + const parentText = parent ? ` on ${parent}` : ''; | |
| 36 | + const keyText = key ? ` for key "${key}"` : ''; | |
| 37 | + throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`); | |
| 38 | +} | |
| 39 | + | |
| 40 | +function prettyTypeName(typ: any): string { | |
| 41 | + if (Array.isArray(typ)) { | |
| 42 | + if (typ.length === 2 && typ[0] === undefined) { | |
| 43 | + return `an optional ${prettyTypeName(typ[1])}`; | |
| 44 | + } else { | |
| 45 | + return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`; | |
| 46 | + } | |
| 47 | + } else if (typeof typ === "object" && typ.literal !== undefined) { | |
| 48 | + return typ.literal; | |
| 49 | + } else { | |
| 50 | + return typeof typ; | |
| 51 | + } | |
| 52 | +} | |
| 53 | + | |
| 54 | +function jsonToJSProps(typ: any): any { | |
| 55 | + if (typ.jsonToJS === undefined) { | |
| 56 | + const map: any = {}; | |
| 57 | + typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ }); | |
| 58 | + typ.jsonToJS = map; | |
| 59 | + } | |
| 60 | + return typ.jsonToJS; | |
| 61 | +} | |
| 62 | + | |
| 63 | +function jsToJSONProps(typ: any): any { | |
| 64 | + if (typ.jsToJSON === undefined) { | |
| 65 | + const map: any = {}; | |
| 66 | + typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ }); | |
| 67 | + typ.jsToJSON = map; | |
| 68 | + } | |
| 69 | + return typ.jsToJSON; | |
| 70 | +} | |
| 71 | + | |
| 72 | +function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any { | |
| 73 | + function transformPrimitive(typ: string, val: any): any { | |
| 74 | + if (typeof typ === typeof val) return val; | |
| 75 | + return invalidValue(typ, val, key, parent); | |
| 76 | + } | |
| 77 | + | |
| 78 | + function transformUnion(typs: any[], val: any): any { | |
| 79 | + // val must validate against one typ in typs | |
| 80 | + const l = typs.length; | |
| 81 | + for (let i = 0; i < l; i++) { | |
| 82 | + const typ = typs[i]; | |
| 83 | + try { | |
| 84 | + return transform(val, typ, getProps); | |
| 85 | + } catch (_) {} | |
| 86 | + } | |
| 87 | + return invalidValue(typs, val, key, parent); | |
| 88 | + } | |
| 89 | + | |
| 90 | + function transformEnum(cases: string[], val: any): any { | |
| 91 | + if (cases.indexOf(val) !== -1) return val; | |
| 92 | + return invalidValue(cases.map(a => { return l(a); }), val, key, parent); | |
| 93 | + } | |
| 94 | + | |
| 95 | + function transformArray(typ: any, val: any): any { | |
| 96 | + // val must be an array with no invalid elements | |
| 97 | + if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent); | |
| 98 | + return val.map(el => transform(el, typ, getProps)); | |
| 99 | + } | |
| 100 | + | |
| 101 | + function transformDate(val: any): any { | |
| 102 | + if (val === null) { | |
| 103 | + return null; | |
| 104 | + } | |
| 105 | + const d = new Date(val); | |
| 106 | + if (isNaN(d.valueOf())) { | |
| 107 | + return invalidValue(l("Date"), val, key, parent); | |
| 108 | + } | |
| 109 | + return d; | |
| 110 | + } | |
| 111 | + | |
| 112 | + function transformObject(props: { [k: string]: any }, additional: any, val: any): any { | |
| 113 | + if (val === null || typeof val !== "object" || Array.isArray(val)) { | |
| 114 | + return invalidValue(l(ref || "object"), val, key, parent); | |
| 115 | + } | |
| 116 | + const result: any = {}; | |
| 117 | + Object.getOwnPropertyNames(props).forEach(key => { | |
| 118 | + const prop = props[key]; | |
| 119 | + const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined; | |
| 120 | + result[prop.key] = transform(v, prop.typ, getProps, key, ref); | |
| 121 | + }); | |
| 122 | + Object.getOwnPropertyNames(val).forEach(key => { | |
| 123 | + if (!Object.prototype.hasOwnProperty.call(props, key)) { | |
| 124 | + result[key] = transform(val[key], additional, getProps, key, ref); | |
| 125 | + } | |
| 126 | + }); | |
| 127 | + return result; | |
| 128 | + } | |
| 129 | + | |
| 130 | + if (typ === "any") return val; | |
| 131 | + if (typ === null) { | |
| 132 | + if (val === null) return val; | |
| 133 | + return invalidValue(typ, val, key, parent); | |
| 134 | + } | |
| 135 | + if (typ === false) return invalidValue(typ, val, key, parent); | |
| 136 | + let ref: any = undefined; | |
| 137 | + while (typeof typ === "object" && typ.ref !== undefined) { | |
| 138 | + ref = typ.ref; | |
| 139 | + typ = typeMap[typ.ref]; | |
| 140 | + } | |
| 141 | + if (Array.isArray(typ)) return transformEnum(typ, val); | |
| 142 | + if (typeof typ === "object") { | |
| 143 | + return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val) | |
| 144 | + : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val) | |
| 145 | + : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val) | |
| 146 | + : invalidValue(typ, val, key, parent); | |
| 147 | + } | |
| 148 | + // Numbers can be parsed by Date but shouldn't be. | |
| 149 | + if (typ === Date && typeof val !== "number") return transformDate(val); | |
| 150 | + return transformPrimitive(typ, val); | |
| 151 | +} | |
| 152 | + | |
| 153 | +function cast<T>(val: any, typ: any): T { | |
| 154 | + return transform(val, typ, jsonToJSProps); | |
| 155 | +} | |
| 156 | + | |
| 157 | +function uncast<T>(val: T, typ: any): any { | |
| 158 | + return transform(val, typ, jsToJSONProps); | |
| 159 | +} | |
| 160 | + | |
| 161 | +function l(typ: any) { | |
| 162 | + return { literal: typ }; | |
| 163 | +} | |
| 164 | + | |
| 165 | +function a(typ: any) { | |
| 166 | + return { arrayItems: typ }; | |
| 167 | +} | |
| 168 | + | |
| 169 | +function u(...typs: any[]) { | |
| 170 | + return { unionMembers: typs }; | |
| 171 | +} | |
| 172 | + | |
| 173 | +function o(props: any[], additional: any) { | |
| 174 | + return { props, additional }; | |
| 175 | +} | |
| 176 | + | |
| 177 | +function m(additional: any) { | |
| 178 | + const props: any[] = []; | |
| 179 | + return { props, additional }; | |
| 180 | +} | |
| 181 | + | |
| 182 | +function r(name: string) { | |
| 183 | + return { ref: name }; | |
| 184 | +} | |
| 185 | + | |
| 186 | +const typeMap: any = { | |
| 187 | + "TopLevel": o([ | |
| 188 | + { json: "alternators", js: "alternators", typ: u(undefined, m(r("Alternator"))) }, | |
| 189 | + ], "any"), | |
| 190 | + "Alternator": o([ | |
| 191 | + { json: "name", js: "name", typ: u(undefined, "") }, | |
| 192 | + { json: "voltage", js: "voltage", typ: u(undefined, 3.14) }, | |
| 193 | + ], "any"), | |
| 194 | +}; |
No generated files match these filters.