Test case
24 generated files · +2,086 −0test/inputs/schema/pattern-properties-map.schema
Aschema-cplusplusdefault / quicktype.hpp+132 −0
| @@ -0,0 +1,132 @@ | ||
| 1 | +// To parse this JSON data, first install | |
| 2 | +// | |
| 3 | +// json.hpp https://github.com/nlohmann/json | |
| 4 | +// | |
| 5 | +// Then include this file, and then do | |
| 6 | +// | |
| 7 | +// TopLevel data = nlohmann::json::parse(jsonString); | |
| 8 | + | |
| 9 | +#pragma once | |
| 10 | + | |
| 11 | +#include <optional> | |
| 12 | +#include "json.hpp" | |
| 13 | + | |
| 14 | +#include <optional> | |
| 15 | +#include <stdexcept> | |
| 16 | +#include <regex> | |
| 17 | + | |
| 18 | +#ifndef NLOHMANN_OPT_HELPER | |
| 19 | +#define NLOHMANN_OPT_HELPER | |
| 20 | +namespace nlohmann { | |
| 21 | + template <typename T> | |
| 22 | + struct adl_serializer<std::shared_ptr<T>> { | |
| 23 | + static void to_json(json & j, const std::shared_ptr<T> & opt) { | |
| 24 | + if (!opt) j = nullptr; else j = *opt; | |
| 25 | + } | |
| 26 | + | |
| 27 | + static std::shared_ptr<T> from_json(const json & j) { | |
| 28 | + if (j.is_null()) return std::shared_ptr<T>(); else return std::make_shared<T>(j.get<T>()); | |
| 29 | + } | |
| 30 | + }; | |
| 31 | + template <typename T> | |
| 32 | + struct adl_serializer<std::optional<T>> { | |
| 33 | + static void to_json(json & j, const std::optional<T> & opt) { | |
| 34 | + if (!opt) j = nullptr; else j = *opt; | |
| 35 | + } | |
| 36 | + | |
| 37 | + static std::optional<T> from_json(const json & j) { | |
| 38 | + if (j.is_null()) return std::optional<T>(); else return std::make_optional<T>(j.get<T>()); | |
| 39 | + } | |
| 40 | + }; | |
| 41 | +} | |
| 42 | +#endif | |
| 43 | + | |
| 44 | +namespace quicktype { | |
| 45 | + using nlohmann::json; | |
| 46 | + | |
| 47 | + #ifndef NLOHMANN_UNTYPED_quicktype_HELPER | |
| 48 | + #define NLOHMANN_UNTYPED_quicktype_HELPER | |
| 49 | + inline json get_untyped(const json & j, const char * property) { | |
| 50 | + if (j.find(property) != j.end()) { | |
| 51 | + return j.at(property).get<json>(); | |
| 52 | + } | |
| 53 | + return json(); | |
| 54 | + } | |
| 55 | + | |
| 56 | + inline json get_untyped(const json & j, std::string property) { | |
| 57 | + return get_untyped(j, property.data()); | |
| 58 | + } | |
| 59 | + #endif | |
| 60 | + | |
| 61 | + #ifndef NLOHMANN_OPTIONAL_quicktype_HELPER | |
| 62 | + #define NLOHMANN_OPTIONAL_quicktype_HELPER | |
| 63 | + template <typename T> | |
| 64 | + inline std::shared_ptr<T> get_heap_optional(const json & j, const char * property) { | |
| 65 | + auto it = j.find(property); | |
| 66 | + if (it != j.end() && !it->is_null()) { | |
| 67 | + return j.at(property).get<std::shared_ptr<T>>(); | |
| 68 | + } | |
| 69 | + return std::shared_ptr<T>(); | |
| 70 | + } | |
| 71 | + | |
| 72 | + template <typename T> | |
| 73 | + inline std::shared_ptr<T> get_heap_optional(const json & j, std::string property) { | |
| 74 | + return get_heap_optional<T>(j, property.data()); | |
| 75 | + } | |
| 76 | + template <typename T> | |
| 77 | + inline std::optional<T> get_stack_optional(const json & j, const char * property) { | |
| 78 | + auto it = j.find(property); | |
| 79 | + if (it != j.end() && !it->is_null()) { | |
| 80 | + return j.at(property).get<std::optional<T>>(); | |
| 81 | + } | |
| 82 | + return std::optional<T>(); | |
| 83 | + } | |
| 84 | + | |
| 85 | + template <typename T> | |
| 86 | + inline std::optional<T> get_stack_optional(const json & j, std::string property) { | |
| 87 | + return get_stack_optional<T>(j, property.data()); | |
| 88 | + } | |
| 89 | + #endif | |
| 90 | + | |
| 91 | + class TopLevel { | |
| 92 | + public: | |
| 93 | + TopLevel() = default; | |
| 94 | + virtual ~TopLevel() = default; | |
| 95 | + | |
| 96 | + private: | |
| 97 | + std::optional<std::map<std::string, nlohmann::json>> a1; | |
| 98 | + std::optional<std::map<std::string, std::string>> a2; | |
| 99 | + std::optional<std::map<std::string, int64_t>> a3; | |
| 100 | + | |
| 101 | + public: | |
| 102 | + const std::optional<std::map<std::string, nlohmann::json>> & get_a1() const { return a1; } | |
| 103 | + std::optional<std::map<std::string, nlohmann::json>> & get_mutable_a1() { return a1; } | |
| 104 | + void set_a1(const std::optional<std::map<std::string, nlohmann::json>> & value) { this->a1 = value; } | |
| 105 | + | |
| 106 | + const std::optional<std::map<std::string, std::string>> & get_a2() const { return a2; } | |
| 107 | + std::optional<std::map<std::string, std::string>> & get_mutable_a2() { return a2; } | |
| 108 | + void set_a2(const std::optional<std::map<std::string, std::string>> & value) { this->a2 = value; } | |
| 109 | + | |
| 110 | + const std::optional<std::map<std::string, int64_t>> & get_a3() const { return a3; } | |
| 111 | + std::optional<std::map<std::string, int64_t>> & get_mutable_a3() { return a3; } | |
| 112 | + void set_a3(const std::optional<std::map<std::string, int64_t>> & value) { this->a3 = value; } | |
| 113 | + }; | |
| 114 | +} | |
| 115 | + | |
| 116 | +namespace quicktype { | |
| 117 | + void from_json(const json & j, TopLevel & x); | |
| 118 | + void to_json(json & j, const TopLevel & x); | |
| 119 | + | |
| 120 | + inline void from_json(const json & j, TopLevel& x) { | |
| 121 | + x.set_a1(get_stack_optional<std::map<std::string, nlohmann::json>>(j, "a1")); | |
| 122 | + x.set_a2(get_stack_optional<std::map<std::string, std::string>>(j, "a2")); | |
| 123 | + x.set_a3(get_stack_optional<std::map<std::string, int64_t>>(j, "a3")); | |
| 124 | + } | |
| 125 | + | |
| 126 | + inline void to_json(json & j, const TopLevel & x) { | |
| 127 | + j = json::object(); | |
| 128 | + j["a1"] = x.get_a1(); | |
| 129 | + j["a2"] = x.get_a2(); | |
| 130 | + j["a3"] = x.get_a3(); | |
| 131 | + } | |
| 132 | +} |
Aschema-csharp-recordsdefault / QuickType.cs+67 −0
| @@ -0,0 +1,67 @@ | ||
| 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("a1", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 29 | + public Dictionary<string, object>? A1 { get; set; } | |
| 30 | + | |
| 31 | + [JsonProperty("a2", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 32 | + public Dictionary<string, string>? A2 { get; set; } | |
| 33 | + | |
| 34 | + [JsonProperty("a3", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 35 | + public Dictionary<string, long>? A3 { get; set; } | |
| 36 | + } | |
| 37 | + | |
| 38 | + public partial record TopLevel | |
| 39 | + { | |
| 40 | + public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings); | |
| 41 | + } | |
| 42 | + | |
| 43 | + public static partial class Serialize | |
| 44 | + { | |
| 45 | + public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings); | |
| 46 | + } | |
| 47 | + | |
| 48 | + internal static partial class Converter | |
| 49 | + { | |
| 50 | + public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings | |
| 51 | + { | |
| 52 | + MetadataPropertyHandling = MetadataPropertyHandling.Ignore, | |
| 53 | + DateParseHandling = DateParseHandling.None, | |
| 54 | + Converters = | |
| 55 | + { | |
| 56 | + new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal } | |
| 57 | + }, | |
| 58 | + }; | |
| 59 | + } | |
| 60 | +} | |
| 61 | +#pragma warning restore CS8618 | |
| 62 | +#pragma warning restore CS8601 | |
| 63 | +#pragma warning restore CS8602 | |
| 64 | +#pragma warning restore CS8603 | |
| 65 | +#pragma warning restore CS8604 | |
| 66 | +#pragma warning restore CS8625 | |
| 67 | +#pragma warning restore CS8765 |
Aschema-csharp-SystemTextJsondefault / QuickType.cs+174 −0
| @@ -0,0 +1,174 @@ | ||
| 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("a1")] | |
| 27 | + public Dictionary<string, object>? A1 { get; set; } | |
| 28 | + | |
| 29 | + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] | |
| 30 | + [JsonPropertyName("a2")] | |
| 31 | + public Dictionary<string, string>? A2 { get; set; } | |
| 32 | + | |
| 33 | + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] | |
| 34 | + [JsonPropertyName("a3")] | |
| 35 | + public Dictionary<string, long>? A3 { get; set; } | |
| 36 | + } | |
| 37 | + | |
| 38 | + public partial class TopLevel | |
| 39 | + { | |
| 40 | + public static TopLevel FromJson(string json) => JsonSerializer.Deserialize<TopLevel>(json, QuickType.Converter.Settings); | |
| 41 | + } | |
| 42 | + | |
| 43 | + public static partial class Serialize | |
| 44 | + { | |
| 45 | + public static string ToJson(this TopLevel self) => JsonSerializer.Serialize(self, QuickType.Converter.Settings); | |
| 46 | + } | |
| 47 | + | |
| 48 | + internal static partial class Converter | |
| 49 | + { | |
| 50 | + public static readonly JsonSerializerOptions Settings = new(JsonSerializerDefaults.General) | |
| 51 | + { | |
| 52 | + Converters = | |
| 53 | + { | |
| 54 | + new DateOnlyConverter(), | |
| 55 | + new TimeOnlyConverter(), | |
| 56 | + IsoDateTimeOffsetConverter.Singleton | |
| 57 | + }, | |
| 58 | + }; | |
| 59 | + } | |
| 60 | + | |
| 61 | + public class DateOnlyConverter : JsonConverter<DateOnly> | |
| 62 | + { | |
| 63 | + private readonly string serializationFormat; | |
| 64 | + public DateOnlyConverter() : this(null) { } | |
| 65 | + | |
| 66 | + public DateOnlyConverter(string? serializationFormat) | |
| 67 | + { | |
| 68 | + this.serializationFormat = serializationFormat ?? "yyyy-MM-dd"; | |
| 69 | + } | |
| 70 | + | |
| 71 | + public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
| 72 | + { | |
| 73 | + var value = reader.GetString(); | |
| 74 | + return DateOnly.Parse(value!); | |
| 75 | + } | |
| 76 | + | |
| 77 | + public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options) | |
| 78 | + => writer.WriteStringValue(value.ToString(serializationFormat)); | |
| 79 | + } | |
| 80 | + | |
| 81 | + public class TimeOnlyConverter : JsonConverter<TimeOnly> | |
| 82 | + { | |
| 83 | + private readonly string serializationFormat; | |
| 84 | + | |
| 85 | + public TimeOnlyConverter() : this(null) { } | |
| 86 | + | |
| 87 | + public TimeOnlyConverter(string? serializationFormat) | |
| 88 | + { | |
| 89 | + this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff"; | |
| 90 | + } | |
| 91 | + | |
| 92 | + public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
| 93 | + { | |
| 94 | + var value = reader.GetString(); | |
| 95 | + return TimeOnly.Parse(value!); | |
| 96 | + } | |
| 97 | + | |
| 98 | + public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options) | |
| 99 | + => writer.WriteStringValue(value.ToString(serializationFormat)); | |
| 100 | + } | |
| 101 | + | |
| 102 | + internal class IsoDateTimeOffsetConverter : JsonConverter<DateTimeOffset> | |
| 103 | + { | |
| 104 | + public override bool CanConvert(Type t) => t == typeof(DateTimeOffset); | |
| 105 | + | |
| 106 | + private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; | |
| 107 | + | |
| 108 | + private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind; | |
| 109 | + private string? _dateTimeFormat; | |
| 110 | + private CultureInfo? _culture; | |
| 111 | + | |
| 112 | + public DateTimeStyles DateTimeStyles | |
| 113 | + { | |
| 114 | + get => _dateTimeStyles; | |
| 115 | + set => _dateTimeStyles = value; | |
| 116 | + } | |
| 117 | + | |
| 118 | + public string? DateTimeFormat | |
| 119 | + { | |
| 120 | + get => _dateTimeFormat ?? string.Empty; | |
| 121 | + set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value; | |
| 122 | + } | |
| 123 | + | |
| 124 | + public CultureInfo Culture | |
| 125 | + { | |
| 126 | + get => _culture ?? CultureInfo.CurrentCulture; | |
| 127 | + set => _culture = value; | |
| 128 | + } | |
| 129 | + | |
| 130 | + public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options) | |
| 131 | + { | |
| 132 | + string text; | |
| 133 | + | |
| 134 | + | |
| 135 | + if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal | |
| 136 | + || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal) | |
| 137 | + { | |
| 138 | + value = value.ToUniversalTime(); | |
| 139 | + } | |
| 140 | + | |
| 141 | + text = value.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture); | |
| 142 | + | |
| 143 | + writer.WriteStringValue(text); | |
| 144 | + } | |
| 145 | + | |
| 146 | + public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
| 147 | + { | |
| 148 | + string? dateText = reader.GetString(); | |
| 149 | + | |
| 150 | + if (string.IsNullOrEmpty(dateText) == false) | |
| 151 | + { | |
| 152 | + if (!string.IsNullOrEmpty(_dateTimeFormat)) | |
| 153 | + { | |
| 154 | + return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles); | |
| 155 | + } | |
| 156 | + else | |
| 157 | + { | |
| 158 | + return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles); | |
| 159 | + } | |
| 160 | + } | |
| 161 | + else | |
| 162 | + { | |
| 163 | + return default(DateTimeOffset); | |
| 164 | + } | |
| 165 | + } | |
| 166 | + | |
| 167 | + | |
| 168 | + public static readonly IsoDateTimeOffsetConverter Singleton = new IsoDateTimeOffsetConverter(); | |
| 169 | + } | |
| 170 | +} | |
| 171 | +#pragma warning restore CS8618 | |
| 172 | +#pragma warning restore CS8601 | |
| 173 | +#pragma warning restore CS8602 | |
| 174 | +#pragma warning restore CS8603 |
Aschema-csharpdefault / QuickType.cs+67 −0
| @@ -0,0 +1,67 @@ | ||
| 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("a1", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 29 | + public Dictionary<string, object>? A1 { get; set; } | |
| 30 | + | |
| 31 | + [JsonProperty("a2", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 32 | + public Dictionary<string, string>? A2 { get; set; } | |
| 33 | + | |
| 34 | + [JsonProperty("a3", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 35 | + public Dictionary<string, long>? A3 { get; set; } | |
| 36 | + } | |
| 37 | + | |
| 38 | + public partial class TopLevel | |
| 39 | + { | |
| 40 | + public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings); | |
| 41 | + } | |
| 42 | + | |
| 43 | + public static partial class Serialize | |
| 44 | + { | |
| 45 | + public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings); | |
| 46 | + } | |
| 47 | + | |
| 48 | + internal static partial class Converter | |
| 49 | + { | |
| 50 | + public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings | |
| 51 | + { | |
| 52 | + MetadataPropertyHandling = MetadataPropertyHandling.Ignore, | |
| 53 | + DateParseHandling = DateParseHandling.None, | |
| 54 | + Converters = | |
| 55 | + { | |
| 56 | + new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal } | |
| 57 | + }, | |
| 58 | + }; | |
| 59 | + } | |
| 60 | +} | |
| 61 | +#pragma warning restore CS8618 | |
| 62 | +#pragma warning restore CS8601 | |
| 63 | +#pragma warning restore CS8602 | |
| 64 | +#pragma warning restore CS8603 | |
| 65 | +#pragma warning restore CS8604 | |
| 66 | +#pragma warning restore CS8625 | |
| 67 | +#pragma warning restore CS8765 |
Aschema-dartdefault / TopLevel.dart+33 −0
| @@ -0,0 +1,33 @@ | ||
| 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, dynamic>? a1; | |
| 13 | + final Map<String, String>? a2; | |
| 14 | + final Map<String, int>? a3; | |
| 15 | + | |
| 16 | + TopLevel({ | |
| 17 | + this.a1, | |
| 18 | + this.a2, | |
| 19 | + this.a3, | |
| 20 | + }); | |
| 21 | + | |
| 22 | + factory TopLevel.fromJson(Map<String, dynamic> json) => TopLevel( | |
| 23 | + a1: Map.from(json["a1"]!).map((k, v) => MapEntry<String, dynamic>(k, v)), | |
| 24 | + a2: Map.from(json["a2"]!).map((k, v) => MapEntry<String, String>(k, v)), | |
| 25 | + a3: Map.from(json["a3"]!).map((k, v) => MapEntry<String, int>(k, v)), | |
| 26 | + ); | |
| 27 | + | |
| 28 | + Map<String, dynamic> toJson() => { | |
| 29 | + "a1": Map.from(a1!).map((k, v) => MapEntry<String, dynamic>(k, v)), | |
| 30 | + "a2": Map.from(a2!).map((k, v) => MapEntry<String, dynamic>(k, v)), | |
| 31 | + "a3": Map.from(a3!).map((k, v) => MapEntry<String, dynamic>(k, v)), | |
| 32 | + }; | |
| 33 | +} |
Aschema-elmdefault / QuickType.elm+57 −0
| @@ -0,0 +1,57 @@ | ||
| 1 | +-- To decode the JSON data, add this file to your project, run | |
| 2 | +-- | |
| 3 | +-- elm install NoRedInk/elm-json-decode-pipeline | |
| 4 | +-- | |
| 5 | +-- add these imports | |
| 6 | +-- | |
| 7 | +-- import Json.Decode exposing (decodeString) | |
| 8 | +-- import QuickType exposing (quickType) | |
| 9 | +-- | |
| 10 | +-- and you're off to the races with | |
| 11 | +-- | |
| 12 | +-- decodeString quickType myJsonString | |
| 13 | + | |
| 14 | +module QuickType exposing | |
| 15 | + ( QuickType | |
| 16 | + , quickTypeToString | |
| 17 | + , quickType | |
| 18 | + ) | |
| 19 | + | |
| 20 | +import Json.Decode as Jdec | |
| 21 | +import Json.Decode.Pipeline as Jpipe | |
| 22 | +import Json.Encode as Jenc | |
| 23 | +import Dict exposing (Dict) | |
| 24 | + | |
| 25 | +type alias QuickType = | |
| 26 | + { a1 : Maybe (Dict String Jdec.Value) | |
| 27 | + , a2 : Maybe (Dict String String) | |
| 28 | + , a3 : Maybe (Dict String Int) | |
| 29 | + } | |
| 30 | + | |
| 31 | +-- decoders and encoders | |
| 32 | + | |
| 33 | +quickTypeToString : QuickType -> String | |
| 34 | +quickTypeToString r = Jenc.encode 0 (encodeQuickType r) | |
| 35 | + | |
| 36 | +quickType : Jdec.Decoder QuickType | |
| 37 | +quickType = | |
| 38 | + Jdec.succeed QuickType | |
| 39 | + |> Jpipe.optional "a1" (Jdec.nullable (Jdec.dict Jdec.value)) Nothing | |
| 40 | + |> Jpipe.optional "a2" (Jdec.nullable (Jdec.dict Jdec.string)) Nothing | |
| 41 | + |> Jpipe.optional "a3" (Jdec.nullable (Jdec.dict Jdec.int)) Nothing | |
| 42 | + | |
| 43 | +encodeQuickType : QuickType -> Jenc.Value | |
| 44 | +encodeQuickType x = | |
| 45 | + Jenc.object | |
| 46 | + [ ("a1", makeNullableEncoder (Jenc.dict identity identity) x.a1) | |
| 47 | + , ("a2", makeNullableEncoder (Jenc.dict identity Jenc.string) x.a2) | |
| 48 | + , ("a3", makeNullableEncoder (Jenc.dict identity Jenc.int) x.a3) | |
| 49 | + ] | |
| 50 | + | |
| 51 | +--- encoder helpers | |
| 52 | + | |
| 53 | +makeNullableEncoder : (a -> Jenc.Value) -> Maybe a -> Jenc.Value | |
| 54 | +makeNullableEncoder f m = | |
| 55 | + case m of | |
| 56 | + Just x -> f x | |
| 57 | + Nothing -> Jenc.null |
Aschema-flowdefault / TopLevel.js+193 −0
| @@ -0,0 +1,193 @@ | ||
| 1 | +// @flow | |
| 2 | + | |
| 3 | +// To parse this data: | |
| 4 | +// | |
| 5 | +// const Convert = require("./TopLevel"); | |
| 6 | +// | |
| 7 | +// const topLevel = Convert.toTopLevel(json); | |
| 8 | +// | |
| 9 | +// These functions will throw an error if the JSON doesn't | |
| 10 | +// match the expected interface, even if the JSON is valid. | |
| 11 | + | |
| 12 | +export type TopLevel = { | |
| 13 | + a1?: { [key: string]: mixed }; | |
| 14 | + a2?: { [key: string]: string }; | |
| 15 | + a3?: { [key: string]: number }; | |
| 16 | + [property: string]: mixed; | |
| 17 | +}; | |
| 18 | + | |
| 19 | +// Converts JSON strings to/from your types | |
| 20 | +// and asserts the results of JSON.parse at runtime | |
| 21 | +function toTopLevel(json: string): TopLevel { | |
| 22 | + return cast(JSON.parse(json), r("TopLevel")); | |
| 23 | +} | |
| 24 | + | |
| 25 | +function topLevelToJson(value: TopLevel): string { | |
| 26 | + return JSON.stringify(uncast(value, r("TopLevel")), null, 2); | |
| 27 | +} | |
| 28 | + | |
| 29 | +function invalidValue(typ: any, val: any, key: any, parent: any = '') { | |
| 30 | + const prettyTyp = prettyTypeName(typ); | |
| 31 | + const parentText = parent ? ` on ${parent}` : ''; | |
| 32 | + const keyText = key ? ` for key "${key}"` : ''; | |
| 33 | + throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`); | |
| 34 | +} | |
| 35 | + | |
| 36 | +function prettyTypeName(typ: any): string { | |
| 37 | + if (Array.isArray(typ)) { | |
| 38 | + if (typ.length === 2 && typ[0] === undefined) { | |
| 39 | + return `an optional ${prettyTypeName(typ[1])}`; | |
| 40 | + } else { | |
| 41 | + return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`; | |
| 42 | + } | |
| 43 | + } else if (typeof typ === "object" && typ.literal !== undefined) { | |
| 44 | + return typ.literal; | |
| 45 | + } else { | |
| 46 | + return typeof typ; | |
| 47 | + } | |
| 48 | +} | |
| 49 | + | |
| 50 | +function jsonToJSProps(typ: any): any { | |
| 51 | + if (typ.jsonToJS === undefined) { | |
| 52 | + const map: any = {}; | |
| 53 | + typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ }); | |
| 54 | + typ.jsonToJS = map; | |
| 55 | + } | |
| 56 | + return typ.jsonToJS; | |
| 57 | +} | |
| 58 | + | |
| 59 | +function jsToJSONProps(typ: any): any { | |
| 60 | + if (typ.jsToJSON === undefined) { | |
| 61 | + const map: any = {}; | |
| 62 | + typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ }); | |
| 63 | + typ.jsToJSON = map; | |
| 64 | + } | |
| 65 | + return typ.jsToJSON; | |
| 66 | +} | |
| 67 | + | |
| 68 | +function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any { | |
| 69 | + function transformPrimitive(typ: string, val: any): any { | |
| 70 | + if (typeof typ === typeof val) return val; | |
| 71 | + return invalidValue(typ, val, key, parent); | |
| 72 | + } | |
| 73 | + | |
| 74 | + function transformUnion(typs: any[], val: any): any { | |
| 75 | + // val must validate against one typ in typs | |
| 76 | + const l = typs.length; | |
| 77 | + for (let i = 0; i < l; i++) { | |
| 78 | + const typ = typs[i]; | |
| 79 | + try { | |
| 80 | + return transform(val, typ, getProps); | |
| 81 | + } catch (_) {} | |
| 82 | + } | |
| 83 | + return invalidValue(typs, val, key, parent); | |
| 84 | + } | |
| 85 | + | |
| 86 | + function transformEnum(cases: string[], val: any): any { | |
| 87 | + if (cases.indexOf(val) !== -1) return val; | |
| 88 | + return invalidValue(cases.map(a => { return l(a); }), val, key, parent); | |
| 89 | + } | |
| 90 | + | |
| 91 | + function transformArray(typ: any, val: any): any { | |
| 92 | + // val must be an array with no invalid elements | |
| 93 | + if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent); | |
| 94 | + return val.map(el => transform(el, typ, getProps)); | |
| 95 | + } | |
| 96 | + | |
| 97 | + function transformDate(val: any): any { | |
| 98 | + if (val === null) { | |
| 99 | + return null; | |
| 100 | + } | |
| 101 | + const d = new Date(val); | |
| 102 | + if (isNaN(d.valueOf())) { | |
| 103 | + return invalidValue(l("Date"), val, key, parent); | |
| 104 | + } | |
| 105 | + return d; | |
| 106 | + } | |
| 107 | + | |
| 108 | + function transformObject(props: { [k: string]: any }, additional: any, val: any): any { | |
| 109 | + if (val === null || typeof val !== "object" || Array.isArray(val)) { | |
| 110 | + return invalidValue(l(ref || "object"), val, key, parent); | |
| 111 | + } | |
| 112 | + const result: any = {}; | |
| 113 | + Object.getOwnPropertyNames(props).forEach(key => { | |
| 114 | + const prop = props[key]; | |
| 115 | + const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined; | |
| 116 | + result[prop.key] = transform(v, prop.typ, getProps, key, ref); | |
| 117 | + }); | |
| 118 | + Object.getOwnPropertyNames(val).forEach(key => { | |
| 119 | + if (!Object.prototype.hasOwnProperty.call(props, key)) { | |
| 120 | + result[key] = transform(val[key], additional, getProps, key, ref); | |
| 121 | + } | |
| 122 | + }); | |
| 123 | + return result; | |
| 124 | + } | |
| 125 | + | |
| 126 | + if (typ === "any") return val; | |
| 127 | + if (typ === null) { | |
| 128 | + if (val === null) return val; | |
| 129 | + return invalidValue(typ, val, key, parent); | |
| 130 | + } | |
| 131 | + if (typ === false) return invalidValue(typ, val, key, parent); | |
| 132 | + let ref: any = undefined; | |
| 133 | + while (typeof typ === "object" && typ.ref !== undefined) { | |
| 134 | + ref = typ.ref; | |
| 135 | + typ = typeMap[typ.ref]; | |
| 136 | + } | |
| 137 | + if (Array.isArray(typ)) return transformEnum(typ, val); | |
| 138 | + if (typeof typ === "object") { | |
| 139 | + return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val) | |
| 140 | + : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val) | |
| 141 | + : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val) | |
| 142 | + : invalidValue(typ, val, key, parent); | |
| 143 | + } | |
| 144 | + // Numbers can be parsed by Date but shouldn't be. | |
| 145 | + if (typ === Date && typeof val !== "number") return transformDate(val); | |
| 146 | + return transformPrimitive(typ, val); | |
| 147 | +} | |
| 148 | + | |
| 149 | +function cast<T>(val: any, typ: any): T { | |
| 150 | + return transform(val, typ, jsonToJSProps); | |
| 151 | +} | |
| 152 | + | |
| 153 | +function uncast<T>(val: T, typ: any): any { | |
| 154 | + return transform(val, typ, jsToJSONProps); | |
| 155 | +} | |
| 156 | + | |
| 157 | +function l(typ: any) { | |
| 158 | + return { literal: typ }; | |
| 159 | +} | |
| 160 | + | |
| 161 | +function a(typ: any) { | |
| 162 | + return { arrayItems: typ }; | |
| 163 | +} | |
| 164 | + | |
| 165 | +function u(...typs: any[]) { | |
| 166 | + return { unionMembers: typs }; | |
| 167 | +} | |
| 168 | + | |
| 169 | +function o(props: any[], additional: any) { | |
| 170 | + return { props, additional }; | |
| 171 | +} | |
| 172 | + | |
| 173 | +function m(additional: any) { | |
| 174 | + const props: any[] = []; | |
| 175 | + return { props, additional }; | |
| 176 | +} | |
| 177 | + | |
| 178 | +function r(name: string) { | |
| 179 | + return { ref: name }; | |
| 180 | +} | |
| 181 | + | |
| 182 | +const typeMap: any = { | |
| 183 | + "TopLevel": o([ | |
| 184 | + { json: "a1", js: "a1", typ: u(undefined, m("any")) }, | |
| 185 | + { json: "a2", js: "a2", typ: u(undefined, m("")) }, | |
| 186 | + { json: "a3", js: "a3", typ: u(undefined, m(0)) }, | |
| 187 | + ], "any"), | |
| 188 | +}; | |
| 189 | + | |
| 190 | +module.exports = { | |
| 191 | + "topLevelToJson": topLevelToJson, | |
| 192 | + "toTopLevel": toTopLevel, | |
| 193 | +}; |
Aschema-golangdefault / quicktype.go+25 −0
| @@ -0,0 +1,25 @@ | ||
| 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 | + A1 map[string]interface{} `json:"a1,omitempty"` | |
| 23 | + A2 map[string]string `json:"a2,omitempty"` | |
| 24 | + A3 map[string]int64 `json:"a3,omitempty"` | |
| 25 | +} |
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+25 −0
| @@ -0,0 +1,25 @@ | ||
| 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, Object> a1; | |
| 8 | + private Map<String, String> a2; | |
| 9 | + private Map<String, Long> a3; | |
| 10 | + | |
| 11 | + @JsonProperty("a1") | |
| 12 | + public Map<String, Object> getA1() { return a1; } | |
| 13 | + @JsonProperty("a1") | |
| 14 | + public void setA1(Map<String, Object> value) { this.a1 = value; } | |
| 15 | + | |
| 16 | + @JsonProperty("a2") | |
| 17 | + public Map<String, String> getA2() { return a2; } | |
| 18 | + @JsonProperty("a2") | |
| 19 | + public void setA2(Map<String, String> value) { this.a2 = value; } | |
| 20 | + | |
| 21 | + @JsonProperty("a3") | |
| 22 | + public Map<String, Long> getA3() { return a3; } | |
| 23 | + @JsonProperty("a3") | |
| 24 | + public void setA3(Map<String, Long> value) { this.a3 = value; } | |
| 25 | +} |
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+25 −0
| @@ -0,0 +1,25 @@ | ||
| 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, Object> a1; | |
| 8 | + private Map<String, String> a2; | |
| 9 | + private Map<String, Long> a3; | |
| 10 | + | |
| 11 | + @JsonProperty("a1") | |
| 12 | + public Map<String, Object> getA1() { return a1; } | |
| 13 | + @JsonProperty("a1") | |
| 14 | + public void setA1(Map<String, Object> value) { this.a1 = value; } | |
| 15 | + | |
| 16 | + @JsonProperty("a2") | |
| 17 | + public Map<String, String> getA2() { return a2; } | |
| 18 | + @JsonProperty("a2") | |
| 19 | + public void setA2(Map<String, String> value) { this.a2 = value; } | |
| 20 | + | |
| 21 | + @JsonProperty("a3") | |
| 22 | + public Map<String, Long> getA3() { return a3; } | |
| 23 | + @JsonProperty("a3") | |
| 24 | + public void setA3(Map<String, Long> value) { this.a3 = value; } | |
| 25 | +} |
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+25 −0
| @@ -0,0 +1,25 @@ | ||
| 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, Object> a1; | |
| 8 | + private Map<String, String> a2; | |
| 9 | + private Map<String, Long> a3; | |
| 10 | + | |
| 11 | + @JsonProperty("a1") | |
| 12 | + public Map<String, Object> getA1() { return a1; } | |
| 13 | + @JsonProperty("a1") | |
| 14 | + public void setA1(Map<String, Object> value) { this.a1 = value; } | |
| 15 | + | |
| 16 | + @JsonProperty("a2") | |
| 17 | + public Map<String, String> getA2() { return a2; } | |
| 18 | + @JsonProperty("a2") | |
| 19 | + public void setA2(Map<String, String> value) { this.a2 = value; } | |
| 20 | + | |
| 21 | + @JsonProperty("a3") | |
| 22 | + public Map<String, Long> getA3() { return a3; } | |
| 23 | + @JsonProperty("a3") | |
| 24 | + public void setA3(Map<String, Long> value) { this.a3 = value; } | |
| 25 | +} |
Aschema-javascriptdefault / TopLevel.js+184 −0
| @@ -0,0 +1,184 @@ | ||
| 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: "a1", js: "a1", typ: u(undefined, m("any")) }, | |
| 176 | + { json: "a2", js: "a2", typ: u(undefined, m("")) }, | |
| 177 | + { json: "a3", js: "a3", typ: u(undefined, m(0)) }, | |
| 178 | + ], "any"), | |
| 179 | +}; | |
| 180 | + | |
| 181 | +module.exports = { | |
| 182 | + "topLevelToJson": topLevelToJson, | |
| 183 | + "toTopLevel": toTopLevel, | |
| 184 | +}; |
Aschema-kotlinxdefault / TopLevel.kt+18 −0
| @@ -0,0 +1,18 @@ | ||
| 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 a1: JsonObject? = null, | |
| 16 | + val a2: Map<String, String>? = null, | |
| 17 | + val a3: Map<String, Long>? = null | |
| 18 | +) |
Aschema-phpdefault / TopLevel.php+286 −0
| @@ -0,0 +1,286 @@ | ||
| 1 | +<?php | |
| 2 | +declare(strict_types=1); | |
| 3 | + | |
| 4 | +// This is an autogenerated file:TopLevel | |
| 5 | + | |
| 6 | +class TopLevel { | |
| 7 | + private ?stdClass $a1; // json:a1 Optional | |
| 8 | + private ?stdClass $a2; // json:a2 Optional | |
| 9 | + private ?stdClass $a3; // json:a3 Optional | |
| 10 | + | |
| 11 | + /** | |
| 12 | + * @param stdClass|null $a1 | |
| 13 | + * @param stdClass|null $a2 | |
| 14 | + * @param stdClass|null $a3 | |
| 15 | + */ | |
| 16 | + public function __construct(?stdClass $a1, ?stdClass $a2, ?stdClass $a3) { | |
| 17 | + $this->a1 = $a1; | |
| 18 | + $this->a2 = $a2; | |
| 19 | + $this->a3 = $a3; | |
| 20 | + } | |
| 21 | + | |
| 22 | + /** | |
| 23 | + * @param ?stdClass $value | |
| 24 | + * @throws Exception | |
| 25 | + * @return ?stdClass | |
| 26 | + */ | |
| 27 | + public static function fromA1(?stdClass $value): ?stdClass { | |
| 28 | + if (!is_null($value)) { | |
| 29 | + $out = new stdClass(); | |
| 30 | + foreach ($value as $k => $v) { | |
| 31 | + $out->$k = $v; /*any*/ | |
| 32 | + } | |
| 33 | + return $out; | |
| 34 | + } else { | |
| 35 | + return null; | |
| 36 | + } | |
| 37 | + } | |
| 38 | + | |
| 39 | + /** | |
| 40 | + * @throws Exception | |
| 41 | + * @return ?stdClass | |
| 42 | + */ | |
| 43 | + public function toA1(): ?stdClass { | |
| 44 | + if (TopLevel::validateA1($this->a1)) { | |
| 45 | + if (!is_null($this->a1)) { | |
| 46 | + $out = new stdClass(); | |
| 47 | + foreach ($this->a1 as $k => $v) { | |
| 48 | + $out->$k = $v; /*any*/ | |
| 49 | + } | |
| 50 | + return $out; | |
| 51 | + } else { | |
| 52 | + return null; | |
| 53 | + } | |
| 54 | + } | |
| 55 | + throw new Exception('never get to this TopLevel::a1'); | |
| 56 | + } | |
| 57 | + | |
| 58 | + /** | |
| 59 | + * @param stdClass|null | |
| 60 | + * @return bool | |
| 61 | + * @throws Exception | |
| 62 | + */ | |
| 63 | + public static function validateA1(?stdClass $value): bool { | |
| 64 | + if (!is_null($value)) { | |
| 65 | + foreach ($value as $k => $v) { | |
| 66 | + } | |
| 67 | + } | |
| 68 | + return true; | |
| 69 | + } | |
| 70 | + | |
| 71 | + /** | |
| 72 | + * @throws Exception | |
| 73 | + * @return ?stdClass | |
| 74 | + */ | |
| 75 | + public function getA1(): ?stdClass { | |
| 76 | + if (TopLevel::validateA1($this->a1)) { | |
| 77 | + return $this->a1; | |
| 78 | + } | |
| 79 | + throw new Exception('never get to getA1 TopLevel::a1'); | |
| 80 | + } | |
| 81 | + | |
| 82 | + /** | |
| 83 | + * @return ?stdClass | |
| 84 | + */ | |
| 85 | + public static function sampleA1(): ?stdClass { | |
| 86 | + return (function () { | |
| 87 | + $out = new stdClass(); | |
| 88 | + $out->{'TopLevel'} = 'AnyType::TopLevel::a1::31';/*31:a1*/ | |
| 89 | + return $out; | |
| 90 | + })(); /* 31:a1*/ | |
| 91 | + } | |
| 92 | + | |
| 93 | + /** | |
| 94 | + * @param ?stdClass $value | |
| 95 | + * @throws Exception | |
| 96 | + * @return ?stdClass | |
| 97 | + */ | |
| 98 | + public static function fromA2(?stdClass $value): ?stdClass { | |
| 99 | + if (!is_null($value)) { | |
| 100 | + $out = new stdClass(); | |
| 101 | + foreach ($value as $k => $v) { | |
| 102 | + $out->$k = $v; /*string*/ | |
| 103 | + } | |
| 104 | + return $out; | |
| 105 | + } else { | |
| 106 | + return null; | |
| 107 | + } | |
| 108 | + } | |
| 109 | + | |
| 110 | + /** | |
| 111 | + * @throws Exception | |
| 112 | + * @return ?stdClass | |
| 113 | + */ | |
| 114 | + public function toA2(): ?stdClass { | |
| 115 | + if (TopLevel::validateA2($this->a2)) { | |
| 116 | + if (!is_null($this->a2)) { | |
| 117 | + $out = new stdClass(); | |
| 118 | + foreach ($this->a2 as $k => $v) { | |
| 119 | + $out->$k = $v; /*string*/ | |
| 120 | + } | |
| 121 | + return $out; | |
| 122 | + } else { | |
| 123 | + return null; | |
| 124 | + } | |
| 125 | + } | |
| 126 | + throw new Exception('never get to this TopLevel::a2'); | |
| 127 | + } | |
| 128 | + | |
| 129 | + /** | |
| 130 | + * @param stdClass|null | |
| 131 | + * @return bool | |
| 132 | + * @throws Exception | |
| 133 | + */ | |
| 134 | + public static function validateA2(?stdClass $value): bool { | |
| 135 | + if (!is_null($value)) { | |
| 136 | + foreach ($value as $k => $v) { | |
| 137 | + if (!is_string($v)) { | |
| 138 | + throw new Exception("Attribute Error:TopLevel::a2"); | |
| 139 | + } | |
| 140 | + } | |
| 141 | + } | |
| 142 | + return true; | |
| 143 | + } | |
| 144 | + | |
| 145 | + /** | |
| 146 | + * @throws Exception | |
| 147 | + * @return ?stdClass | |
| 148 | + */ | |
| 149 | + public function getA2(): ?stdClass { | |
| 150 | + if (TopLevel::validateA2($this->a2)) { | |
| 151 | + return $this->a2; | |
| 152 | + } | |
| 153 | + throw new Exception('never get to getA2 TopLevel::a2'); | |
| 154 | + } | |
| 155 | + | |
| 156 | + /** | |
| 157 | + * @return ?stdClass | |
| 158 | + */ | |
| 159 | + public static function sampleA2(): ?stdClass { | |
| 160 | + return (function () { | |
| 161 | + $out = new stdClass(); | |
| 162 | + $out->{'TopLevel'} = 'TopLevel::a2::32'; /*32:a2*/ | |
| 163 | + return $out; | |
| 164 | + })(); /* 32:a2*/ | |
| 165 | + } | |
| 166 | + | |
| 167 | + /** | |
| 168 | + * @param ?stdClass $value | |
| 169 | + * @throws Exception | |
| 170 | + * @return ?stdClass | |
| 171 | + */ | |
| 172 | + public static function fromA3(?stdClass $value): ?stdClass { | |
| 173 | + if (!is_null($value)) { | |
| 174 | + $out = new stdClass(); | |
| 175 | + foreach ($value as $k => $v) { | |
| 176 | + $out->$k = $v; /*int*/ | |
| 177 | + } | |
| 178 | + return $out; | |
| 179 | + } else { | |
| 180 | + return null; | |
| 181 | + } | |
| 182 | + } | |
| 183 | + | |
| 184 | + /** | |
| 185 | + * @throws Exception | |
| 186 | + * @return ?stdClass | |
| 187 | + */ | |
| 188 | + public function toA3(): ?stdClass { | |
| 189 | + if (TopLevel::validateA3($this->a3)) { | |
| 190 | + if (!is_null($this->a3)) { | |
| 191 | + $out = new stdClass(); | |
| 192 | + foreach ($this->a3 as $k => $v) { | |
| 193 | + $out->$k = $v; /*int*/ | |
| 194 | + } | |
| 195 | + return $out; | |
| 196 | + } else { | |
| 197 | + return null; | |
| 198 | + } | |
| 199 | + } | |
| 200 | + throw new Exception('never get to this TopLevel::a3'); | |
| 201 | + } | |
| 202 | + | |
| 203 | + /** | |
| 204 | + * @param stdClass|null | |
| 205 | + * @return bool | |
| 206 | + * @throws Exception | |
| 207 | + */ | |
| 208 | + public static function validateA3(?stdClass $value): bool { | |
| 209 | + if (!is_null($value)) { | |
| 210 | + foreach ($value as $k => $v) { | |
| 211 | + if (!is_integer($v)) { | |
| 212 | + throw new Exception("Attribute Error:TopLevel::a3"); | |
| 213 | + } | |
| 214 | + } | |
| 215 | + } | |
| 216 | + return true; | |
| 217 | + } | |
| 218 | + | |
| 219 | + /** | |
| 220 | + * @throws Exception | |
| 221 | + * @return ?stdClass | |
| 222 | + */ | |
| 223 | + public function getA3(): ?stdClass { | |
| 224 | + if (TopLevel::validateA3($this->a3)) { | |
| 225 | + return $this->a3; | |
| 226 | + } | |
| 227 | + throw new Exception('never get to getA3 TopLevel::a3'); | |
| 228 | + } | |
| 229 | + | |
| 230 | + /** | |
| 231 | + * @return ?stdClass | |
| 232 | + */ | |
| 233 | + public static function sampleA3(): ?stdClass { | |
| 234 | + return (function () { | |
| 235 | + $out = new stdClass(); | |
| 236 | + $out->{'TopLevel'} = 33; /*33:a3*/ | |
| 237 | + return $out; | |
| 238 | + })(); /* 33:a3*/ | |
| 239 | + } | |
| 240 | + | |
| 241 | + /** | |
| 242 | + * @throws Exception | |
| 243 | + * @return bool | |
| 244 | + */ | |
| 245 | + public function validate(): bool { | |
| 246 | + return TopLevel::validateA1($this->a1) | |
| 247 | + || TopLevel::validateA2($this->a2) | |
| 248 | + || TopLevel::validateA3($this->a3); | |
| 249 | + } | |
| 250 | + | |
| 251 | + /** | |
| 252 | + * @return stdClass | |
| 253 | + * @throws Exception | |
| 254 | + */ | |
| 255 | + public function to(): stdClass { | |
| 256 | + $out = new stdClass(); | |
| 257 | + $out->{'a1'} = $this->toA1(); | |
| 258 | + $out->{'a2'} = $this->toA2(); | |
| 259 | + $out->{'a3'} = $this->toA3(); | |
| 260 | + return $out; | |
| 261 | + } | |
| 262 | + | |
| 263 | + /** | |
| 264 | + * @param stdClass $obj | |
| 265 | + * @return TopLevel | |
| 266 | + * @throws Exception | |
| 267 | + */ | |
| 268 | + public static function from(stdClass $obj): TopLevel { | |
| 269 | + return new TopLevel( | |
| 270 | + TopLevel::fromA1($obj->{'a1'}) | |
| 271 | + ,TopLevel::fromA2($obj->{'a2'}) | |
| 272 | + ,TopLevel::fromA3($obj->{'a3'}) | |
| 273 | + ); | |
| 274 | + } | |
| 275 | + | |
| 276 | + /** | |
| 277 | + * @return TopLevel | |
| 278 | + */ | |
| 279 | + public static function sample(): TopLevel { | |
| 280 | + return new TopLevel( | |
| 281 | + TopLevel::sampleA1() | |
| 282 | + ,TopLevel::sampleA2() | |
| 283 | + ,TopLevel::sampleA3() | |
| 284 | + ); | |
| 285 | + } | |
| 286 | +} |
Aschema-pythondefault / quicktype.py+72 −0
| @@ -0,0 +1,72 @@ | ||
| 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_dict(f: Callable[[Any], T], x: Any) -> dict[str, T]: | |
| 9 | + assert isinstance(x, dict) | |
| 10 | + return { k: f(v) for (k, v) in x.items() } | |
| 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_str(x: Any) -> str: | |
| 28 | + assert isinstance(x, str) | |
| 29 | + return x | |
| 30 | + | |
| 31 | + | |
| 32 | +def from_int(x: Any) -> int: | |
| 33 | + assert isinstance(x, int) and not isinstance(x, bool) | |
| 34 | + return x | |
| 35 | + | |
| 36 | + | |
| 37 | +def to_class(c: Type[T], x: Any) -> dict: | |
| 38 | + assert isinstance(x, c) | |
| 39 | + return cast(Any, x).to_dict() | |
| 40 | + | |
| 41 | + | |
| 42 | +@dataclass | |
| 43 | +class TopLevel: | |
| 44 | + a1: dict[str, Any] | None = None | |
| 45 | + a2: dict[str, str] | None = None | |
| 46 | + a3: dict[str, int] | None = None | |
| 47 | + | |
| 48 | + @staticmethod | |
| 49 | + def from_dict(obj: Any) -> 'TopLevel': | |
| 50 | + assert isinstance(obj, dict) | |
| 51 | + a1 = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("a1")) | |
| 52 | + a2 = from_union([lambda x: from_dict(from_str, x), from_none], obj.get("a2")) | |
| 53 | + a3 = from_union([lambda x: from_dict(from_int, x), from_none], obj.get("a3")) | |
| 54 | + return TopLevel(a1, a2, a3) | |
| 55 | + | |
| 56 | + def to_dict(self) -> dict: | |
| 57 | + result: dict = {} | |
| 58 | + if self.a1 is not None: | |
| 59 | + result["a1"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.a1) | |
| 60 | + if self.a2 is not None: | |
| 61 | + result["a2"] = from_union([lambda x: from_dict(from_str, x), from_none], self.a2) | |
| 62 | + if self.a3 is not None: | |
| 63 | + result["a3"] = from_union([lambda x: from_dict(from_int, x), from_none], self.a3) | |
| 64 | + return result | |
| 65 | + | |
| 66 | + | |
| 67 | +def top_level_from_dict(s: Any) -> TopLevel: | |
| 68 | + return TopLevel.from_dict(s) | |
| 69 | + | |
| 70 | + | |
| 71 | +def top_level_to_dict(x: TopLevel) -> Any: | |
| 72 | + return to_class(TopLevel, x) |
Aschema-rubydefault / TopLevel.rb+52 −0
| @@ -0,0 +1,52 @@ | ||
| 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.a3&["…"].even? | |
| 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 | + Integer = Strict::Integer | |
| 19 | + Hash = Strict::Hash | |
| 20 | + String = Strict::String | |
| 21 | +end | |
| 22 | + | |
| 23 | +class TopLevel < Dry::Struct | |
| 24 | + attribute :a1, Types::Hash.meta(of: Types::Any).optional | |
| 25 | + attribute :a2, Types::Hash.meta(of: Types::String).optional | |
| 26 | + attribute :a3, Types::Hash.meta(of: Types::Integer).optional | |
| 27 | + | |
| 28 | + def self.from_dynamic!(d) | |
| 29 | + d = Types::Hash[d] | |
| 30 | + new( | |
| 31 | + a1: Types::Hash.optional[d["a1"]]&.map { |k, v| [k, Types::Any[v]] }&.to_h, | |
| 32 | + a2: Types::Hash.optional[d["a2"]]&.map { |k, v| [k, Types::String[v]] }&.to_h, | |
| 33 | + a3: Types::Hash.optional[d["a3"]]&.map { |k, v| [k, Types::Integer[v]] }&.to_h, | |
| 34 | + ) | |
| 35 | + end | |
| 36 | + | |
| 37 | + def self.from_json!(json) | |
| 38 | + from_dynamic!(JSON.parse(json)) | |
| 39 | + end | |
| 40 | + | |
| 41 | + def to_dynamic | |
| 42 | + { | |
| 43 | + "a1" => a1, | |
| 44 | + "a2" => a2, | |
| 45 | + "a3" => a3, | |
| 46 | + } | |
| 47 | + end | |
| 48 | + | |
| 49 | + def to_json(options = nil) | |
| 50 | + JSON.generate(to_dynamic, options) | |
| 51 | + end | |
| 52 | +end |
Aschema-rustdefault / module_under_test.rs+24 −0
| @@ -0,0 +1,24 @@ | ||
| 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 a1: Option<HashMap<String, Option<serde_json::Value>>>, | |
| 20 | + | |
| 21 | + pub a2: Option<HashMap<String, String>>, | |
| 22 | + | |
| 23 | + pub a3: Option<HashMap<String, i64>>, | |
| 24 | +} |
Aschema-scala3-upickledefault / TopLevel.scala+72 −0
| @@ -0,0 +1,72 @@ | ||
| 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 a1 : Option[Map[String, Option[ujson.Value]]] = None, | |
| 70 | + val a2 : Option[Map[String, String]] = None, | |
| 71 | + val a3 : Option[Map[String, Long]] = None | |
| 72 | +) derives OptionPickler.ReadWriter |
Aschema-scala3default / TopLevel.scala+14 −0
| @@ -0,0 +1,14 @@ | ||
| 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 a1 : Option[Map[String, Option[Json]]] = None, | |
| 12 | + val a2 : Option[Map[String, String]] = None, | |
| 13 | + val a3 : Option[Map[String, Long]] = None | |
| 14 | +) derives Encoder.AsObject, Decoder |
Aschema-schemadefault / TopLevel.schema+30 −0
| @@ -0,0 +1,30 @@ | ||
| 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 | + "a1": { | |
| 10 | + "type": "object", | |
| 11 | + "additionalProperties": {} | |
| 12 | + }, | |
| 13 | + "a2": { | |
| 14 | + "type": "object", | |
| 15 | + "additionalProperties": { | |
| 16 | + "type": "string" | |
| 17 | + } | |
| 18 | + }, | |
| 19 | + "a3": { | |
| 20 | + "type": "object", | |
| 21 | + "additionalProperties": { | |
| 22 | + "type": "integer" | |
| 23 | + } | |
| 24 | + } | |
| 25 | + }, | |
| 26 | + "required": [], | |
| 27 | + "title": "TopLevel" | |
| 28 | + } | |
| 29 | + } | |
| 30 | +} |
Aschema-typescriptdefault / TopLevel.ts+188 −0
| @@ -0,0 +1,188 @@ | ||
| 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 | + a1?: { [key: string]: unknown }; | |
| 12 | + a2?: { [key: string]: string }; | |
| 13 | + a3?: { [key: string]: number }; | |
| 14 | + [property: string]: unknown; | |
| 15 | +} | |
| 16 | + | |
| 17 | +// Converts JSON strings to/from your types | |
| 18 | +// and asserts the results of JSON.parse at runtime | |
| 19 | +export class Convert { | |
| 20 | + public static toTopLevel(json: string): TopLevel { | |
| 21 | + return cast(JSON.parse(json), r("TopLevel")); | |
| 22 | + } | |
| 23 | + | |
| 24 | + public static topLevelToJson(value: TopLevel): string { | |
| 25 | + return JSON.stringify(uncast(value, r("TopLevel")), null, 2); | |
| 26 | + } | |
| 27 | +} | |
| 28 | + | |
| 29 | +function invalidValue(typ: any, val: any, key: any, parent: any = ''): never { | |
| 30 | + const prettyTyp = prettyTypeName(typ); | |
| 31 | + const parentText = parent ? ` on ${parent}` : ''; | |
| 32 | + const keyText = key ? ` for key "${key}"` : ''; | |
| 33 | + throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`); | |
| 34 | +} | |
| 35 | + | |
| 36 | +function prettyTypeName(typ: any): string { | |
| 37 | + if (Array.isArray(typ)) { | |
| 38 | + if (typ.length === 2 && typ[0] === undefined) { | |
| 39 | + return `an optional ${prettyTypeName(typ[1])}`; | |
| 40 | + } else { | |
| 41 | + return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`; | |
| 42 | + } | |
| 43 | + } else if (typeof typ === "object" && typ.literal !== undefined) { | |
| 44 | + return typ.literal; | |
| 45 | + } else { | |
| 46 | + return typeof typ; | |
| 47 | + } | |
| 48 | +} | |
| 49 | + | |
| 50 | +function jsonToJSProps(typ: any): any { | |
| 51 | + if (typ.jsonToJS === undefined) { | |
| 52 | + const map: any = {}; | |
| 53 | + typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ }); | |
| 54 | + typ.jsonToJS = map; | |
| 55 | + } | |
| 56 | + return typ.jsonToJS; | |
| 57 | +} | |
| 58 | + | |
| 59 | +function jsToJSONProps(typ: any): any { | |
| 60 | + if (typ.jsToJSON === undefined) { | |
| 61 | + const map: any = {}; | |
| 62 | + typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ }); | |
| 63 | + typ.jsToJSON = map; | |
| 64 | + } | |
| 65 | + return typ.jsToJSON; | |
| 66 | +} | |
| 67 | + | |
| 68 | +function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any { | |
| 69 | + function transformPrimitive(typ: string, val: any): any { | |
| 70 | + if (typeof typ === typeof val) return val; | |
| 71 | + return invalidValue(typ, val, key, parent); | |
| 72 | + } | |
| 73 | + | |
| 74 | + function transformUnion(typs: any[], val: any): any { | |
| 75 | + // val must validate against one typ in typs | |
| 76 | + const l = typs.length; | |
| 77 | + for (let i = 0; i < l; i++) { | |
| 78 | + const typ = typs[i]; | |
| 79 | + try { | |
| 80 | + return transform(val, typ, getProps); | |
| 81 | + } catch (_) {} | |
| 82 | + } | |
| 83 | + return invalidValue(typs, val, key, parent); | |
| 84 | + } | |
| 85 | + | |
| 86 | + function transformEnum(cases: string[], val: any): any { | |
| 87 | + if (cases.indexOf(val) !== -1) return val; | |
| 88 | + return invalidValue(cases.map(a => { return l(a); }), val, key, parent); | |
| 89 | + } | |
| 90 | + | |
| 91 | + function transformArray(typ: any, val: any): any { | |
| 92 | + // val must be an array with no invalid elements | |
| 93 | + if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent); | |
| 94 | + return val.map(el => transform(el, typ, getProps)); | |
| 95 | + } | |
| 96 | + | |
| 97 | + function transformDate(val: any): any { | |
| 98 | + if (val === null) { | |
| 99 | + return null; | |
| 100 | + } | |
| 101 | + const d = new Date(val); | |
| 102 | + if (isNaN(d.valueOf())) { | |
| 103 | + return invalidValue(l("Date"), val, key, parent); | |
| 104 | + } | |
| 105 | + return d; | |
| 106 | + } | |
| 107 | + | |
| 108 | + function transformObject(props: { [k: string]: any }, additional: any, val: any): any { | |
| 109 | + if (val === null || typeof val !== "object" || Array.isArray(val)) { | |
| 110 | + return invalidValue(l(ref || "object"), val, key, parent); | |
| 111 | + } | |
| 112 | + const result: any = {}; | |
| 113 | + Object.getOwnPropertyNames(props).forEach(key => { | |
| 114 | + const prop = props[key]; | |
| 115 | + const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined; | |
| 116 | + result[prop.key] = transform(v, prop.typ, getProps, key, ref); | |
| 117 | + }); | |
| 118 | + Object.getOwnPropertyNames(val).forEach(key => { | |
| 119 | + if (!Object.prototype.hasOwnProperty.call(props, key)) { | |
| 120 | + result[key] = transform(val[key], additional, getProps, key, ref); | |
| 121 | + } | |
| 122 | + }); | |
| 123 | + return result; | |
| 124 | + } | |
| 125 | + | |
| 126 | + if (typ === "any") return val; | |
| 127 | + if (typ === null) { | |
| 128 | + if (val === null) return val; | |
| 129 | + return invalidValue(typ, val, key, parent); | |
| 130 | + } | |
| 131 | + if (typ === false) return invalidValue(typ, val, key, parent); | |
| 132 | + let ref: any = undefined; | |
| 133 | + while (typeof typ === "object" && typ.ref !== undefined) { | |
| 134 | + ref = typ.ref; | |
| 135 | + typ = typeMap[typ.ref]; | |
| 136 | + } | |
| 137 | + if (Array.isArray(typ)) return transformEnum(typ, val); | |
| 138 | + if (typeof typ === "object") { | |
| 139 | + return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val) | |
| 140 | + : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val) | |
| 141 | + : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val) | |
| 142 | + : invalidValue(typ, val, key, parent); | |
| 143 | + } | |
| 144 | + // Numbers can be parsed by Date but shouldn't be. | |
| 145 | + if (typ === Date && typeof val !== "number") return transformDate(val); | |
| 146 | + return transformPrimitive(typ, val); | |
| 147 | +} | |
| 148 | + | |
| 149 | +function cast<T>(val: any, typ: any): T { | |
| 150 | + return transform(val, typ, jsonToJSProps); | |
| 151 | +} | |
| 152 | + | |
| 153 | +function uncast<T>(val: T, typ: any): any { | |
| 154 | + return transform(val, typ, jsToJSONProps); | |
| 155 | +} | |
| 156 | + | |
| 157 | +function l(typ: any) { | |
| 158 | + return { literal: typ }; | |
| 159 | +} | |
| 160 | + | |
| 161 | +function a(typ: any) { | |
| 162 | + return { arrayItems: typ }; | |
| 163 | +} | |
| 164 | + | |
| 165 | +function u(...typs: any[]) { | |
| 166 | + return { unionMembers: typs }; | |
| 167 | +} | |
| 168 | + | |
| 169 | +function o(props: any[], additional: any) { | |
| 170 | + return { props, additional }; | |
| 171 | +} | |
| 172 | + | |
| 173 | +function m(additional: any) { | |
| 174 | + const props: any[] = []; | |
| 175 | + return { props, additional }; | |
| 176 | +} | |
| 177 | + | |
| 178 | +function r(name: string) { | |
| 179 | + return { ref: name }; | |
| 180 | +} | |
| 181 | + | |
| 182 | +const typeMap: any = { | |
| 183 | + "TopLevel": o([ | |
| 184 | + { json: "a1", js: "a1", typ: u(undefined, m("any")) }, | |
| 185 | + { json: "a2", js: "a2", typ: u(undefined, m("")) }, | |
| 186 | + { json: "a3", js: "a3", typ: u(undefined, m(0)) }, | |
| 187 | + ], "any"), | |
| 188 | +}; |
No generated files match these filters.