Test case
40 generated files · +4,198 −0test/inputs/schema/upper-acronym-names.schema
Aschema-cplusplusdefault / quicktype.hpp+248 −0
| @@ -0,0 +1,248 @@ | ||
| 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 IdCardHttp { | |
| 92 | + public: | |
| 93 | + IdCardHttp() = default; | |
| 94 | + virtual ~IdCardHttp() = default; | |
| 95 | + | |
| 96 | + private: | |
| 97 | + std::optional<std::string> value; | |
| 98 | + | |
| 99 | + public: | |
| 100 | + const std::optional<std::string> & get_value() const { return value; } | |
| 101 | + std::optional<std::string> & get_mutable_value() { return value; } | |
| 102 | + void set_value(const std::optional<std::string> & value) { this->value = value; } | |
| 103 | + }; | |
| 104 | + | |
| 105 | + class Point { | |
| 106 | + public: | |
| 107 | + Point() = default; | |
| 108 | + virtual ~Point() = default; | |
| 109 | + | |
| 110 | + private: | |
| 111 | + std::optional<double> latitude; | |
| 112 | + std::optional<double> longitude; | |
| 113 | + | |
| 114 | + public: | |
| 115 | + const std::optional<double> & get_latitude() const { return latitude; } | |
| 116 | + std::optional<double> & get_mutable_latitude() { return latitude; } | |
| 117 | + void set_latitude(const std::optional<double> & value) { this->latitude = value; } | |
| 118 | + | |
| 119 | + const std::optional<double> & get_longitude() const { return longitude; } | |
| 120 | + std::optional<double> & get_mutable_longitude() { return longitude; } | |
| 121 | + void set_longitude(const std::optional<double> & value) { this->longitude = value; } | |
| 122 | + }; | |
| 123 | + | |
| 124 | + enum class ScubaManeuver : int { ASCENT, DESCENT, LEVEL }; | |
| 125 | + | |
| 126 | + class ScubaWaypoint { | |
| 127 | + public: | |
| 128 | + ScubaWaypoint() = default; | |
| 129 | + virtual ~ScubaWaypoint() = default; | |
| 130 | + | |
| 131 | + private: | |
| 132 | + std::optional<double> depth; | |
| 133 | + std::optional<IdCardHttp> id_card; | |
| 134 | + std::optional<Point> location; | |
| 135 | + std::optional<ScubaManeuver> maneuver; | |
| 136 | + | |
| 137 | + public: | |
| 138 | + const std::optional<double> & get_depth() const { return depth; } | |
| 139 | + std::optional<double> & get_mutable_depth() { return depth; } | |
| 140 | + void set_depth(const std::optional<double> & value) { this->depth = value; } | |
| 141 | + | |
| 142 | + const std::optional<IdCardHttp> & get_id_card() const { return id_card; } | |
| 143 | + std::optional<IdCardHttp> & get_mutable_id_card() { return id_card; } | |
| 144 | + void set_id_card(const std::optional<IdCardHttp> & value) { this->id_card = value; } | |
| 145 | + | |
| 146 | + const std::optional<Point> & get_location() const { return location; } | |
| 147 | + std::optional<Point> & get_mutable_location() { return location; } | |
| 148 | + void set_location(const std::optional<Point> & value) { this->location = value; } | |
| 149 | + | |
| 150 | + const std::optional<ScubaManeuver> & get_maneuver() const { return maneuver; } | |
| 151 | + std::optional<ScubaManeuver> & get_mutable_maneuver() { return maneuver; } | |
| 152 | + void set_maneuver(const std::optional<ScubaManeuver> & value) { this->maneuver = value; } | |
| 153 | + }; | |
| 154 | + | |
| 155 | + /** | |
| 156 | + * A SCUBA dive log with waypoints | |
| 157 | + */ | |
| 158 | + class TopLevel { | |
| 159 | + public: | |
| 160 | + TopLevel() = default; | |
| 161 | + virtual ~TopLevel() = default; | |
| 162 | + | |
| 163 | + private: | |
| 164 | + std::optional<std::vector<ScubaWaypoint>> waypoints; | |
| 165 | + | |
| 166 | + public: | |
| 167 | + const std::optional<std::vector<ScubaWaypoint>> & get_waypoints() const { return waypoints; } | |
| 168 | + std::optional<std::vector<ScubaWaypoint>> & get_mutable_waypoints() { return waypoints; } | |
| 169 | + void set_waypoints(const std::optional<std::vector<ScubaWaypoint>> & value) { this->waypoints = value; } | |
| 170 | + }; | |
| 171 | +} | |
| 172 | + | |
| 173 | +namespace quicktype { | |
| 174 | + void from_json(const json & j, IdCardHttp & x); | |
| 175 | + void to_json(json & j, const IdCardHttp & x); | |
| 176 | + | |
| 177 | + void from_json(const json & j, Point & x); | |
| 178 | + void to_json(json & j, const Point & x); | |
| 179 | + | |
| 180 | + void from_json(const json & j, ScubaWaypoint & x); | |
| 181 | + void to_json(json & j, const ScubaWaypoint & x); | |
| 182 | + | |
| 183 | + void from_json(const json & j, TopLevel & x); | |
| 184 | + void to_json(json & j, const TopLevel & x); | |
| 185 | + | |
| 186 | + void from_json(const json & j, ScubaManeuver & x); | |
| 187 | + void to_json(json & j, const ScubaManeuver & x); | |
| 188 | + | |
| 189 | + inline void from_json(const json & j, IdCardHttp& x) { | |
| 190 | + x.set_value(get_stack_optional<std::string>(j, "value")); | |
| 191 | + } | |
| 192 | + | |
| 193 | + inline void to_json(json & j, const IdCardHttp & x) { | |
| 194 | + j = json::object(); | |
| 195 | + j["value"] = x.get_value(); | |
| 196 | + } | |
| 197 | + | |
| 198 | + inline void from_json(const json & j, Point& x) { | |
| 199 | + x.set_latitude(get_stack_optional<double>(j, "latitude")); | |
| 200 | + x.set_longitude(get_stack_optional<double>(j, "longitude")); | |
| 201 | + } | |
| 202 | + | |
| 203 | + inline void to_json(json & j, const Point & x) { | |
| 204 | + j = json::object(); | |
| 205 | + j["latitude"] = x.get_latitude(); | |
| 206 | + j["longitude"] = x.get_longitude(); | |
| 207 | + } | |
| 208 | + | |
| 209 | + inline void from_json(const json & j, ScubaWaypoint& x) { | |
| 210 | + x.set_depth(get_stack_optional<double>(j, "depth")); | |
| 211 | + x.set_id_card(get_stack_optional<IdCardHttp>(j, "idCard")); | |
| 212 | + x.set_location(get_stack_optional<Point>(j, "location")); | |
| 213 | + x.set_maneuver(get_stack_optional<ScubaManeuver>(j, "maneuver")); | |
| 214 | + } | |
| 215 | + | |
| 216 | + inline void to_json(json & j, const ScubaWaypoint & x) { | |
| 217 | + j = json::object(); | |
| 218 | + j["depth"] = x.get_depth(); | |
| 219 | + j["idCard"] = x.get_id_card(); | |
| 220 | + j["location"] = x.get_location(); | |
| 221 | + j["maneuver"] = x.get_maneuver(); | |
| 222 | + } | |
| 223 | + | |
| 224 | + inline void from_json(const json & j, TopLevel& x) { | |
| 225 | + x.set_waypoints(get_stack_optional<std::vector<ScubaWaypoint>>(j, "waypoints")); | |
| 226 | + } | |
| 227 | + | |
| 228 | + inline void to_json(json & j, const TopLevel & x) { | |
| 229 | + j = json::object(); | |
| 230 | + j["waypoints"] = x.get_waypoints(); | |
| 231 | + } | |
| 232 | + | |
| 233 | + inline void from_json(const json & j, ScubaManeuver & x) { | |
| 234 | + if (j == "ASCENT") x = ScubaManeuver::ASCENT; | |
| 235 | + else if (j == "DESCENT") x = ScubaManeuver::DESCENT; | |
| 236 | + else if (j == "LEVEL") x = ScubaManeuver::LEVEL; | |
| 237 | + else { throw std::runtime_error("Cannot deserialize to enumeration \"ScubaManeuver\""); } | |
| 238 | + } | |
| 239 | + | |
| 240 | + inline void to_json(json & j, const ScubaManeuver & x) { | |
| 241 | + switch (x) { | |
| 242 | + case ScubaManeuver::ASCENT: j = "ASCENT"; break; | |
| 243 | + case ScubaManeuver::DESCENT: j = "DESCENT"; break; | |
| 244 | + case ScubaManeuver::LEVEL: j = "LEVEL"; break; | |
| 245 | + default: throw std::runtime_error("Unexpected value in enumeration \"ScubaManeuver\": " + std::to_string(static_cast<int>(x))); | |
| 246 | + } | |
| 247 | + } | |
| 248 | +} |
Aschema-csharp-recordsdefault / QuickType.cs+143 −0
| @@ -0,0 +1,143 @@ | ||
| 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 | + /// <summary> | |
| 27 | + /// A SCUBA dive log with waypoints | |
| 28 | + /// </summary> | |
| 29 | + public partial record TopLevel | |
| 30 | + { | |
| 31 | + [JsonProperty("waypoints", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 32 | + public ScubaWaypoint[]? Waypoints { get; set; } | |
| 33 | + } | |
| 34 | + | |
| 35 | + public partial record ScubaWaypoint | |
| 36 | + { | |
| 37 | + [JsonProperty("depth", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 38 | + public double? Depth { get; set; } | |
| 39 | + | |
| 40 | + [JsonProperty("idCard", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 41 | + public IdCardHttp? IdCard { get; set; } | |
| 42 | + | |
| 43 | + [JsonProperty("location", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 44 | + public Point? Location { get; set; } | |
| 45 | + | |
| 46 | + [JsonProperty("maneuver", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 47 | + public ScubaManeuver? Maneuver { get; set; } | |
| 48 | + } | |
| 49 | + | |
| 50 | + public partial record IdCardHttp | |
| 51 | + { | |
| 52 | + [JsonProperty("value", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 53 | + public string? Value { get; set; } | |
| 54 | + } | |
| 55 | + | |
| 56 | + public partial record Point | |
| 57 | + { | |
| 58 | + [JsonProperty("latitude", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 59 | + public double? Latitude { get; set; } | |
| 60 | + | |
| 61 | + [JsonProperty("longitude", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 62 | + public double? Longitude { get; set; } | |
| 63 | + } | |
| 64 | + | |
| 65 | + public enum ScubaManeuver { Ascent, Descent, Level }; | |
| 66 | + | |
| 67 | + public partial record TopLevel | |
| 68 | + { | |
| 69 | + public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings); | |
| 70 | + } | |
| 71 | + | |
| 72 | + public static partial class Serialize | |
| 73 | + { | |
| 74 | + public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings); | |
| 75 | + } | |
| 76 | + | |
| 77 | + internal static partial class Converter | |
| 78 | + { | |
| 79 | + public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings | |
| 80 | + { | |
| 81 | + MetadataPropertyHandling = MetadataPropertyHandling.Ignore, | |
| 82 | + DateParseHandling = DateParseHandling.None, | |
| 83 | + Converters = | |
| 84 | + { | |
| 85 | + ScubaManeuverConverter.Singleton, | |
| 86 | + new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal } | |
| 87 | + }, | |
| 88 | + }; | |
| 89 | + } | |
| 90 | + | |
| 91 | + internal class ScubaManeuverConverter : JsonConverter | |
| 92 | + { | |
| 93 | + public override bool CanConvert(Type t) => t == typeof(ScubaManeuver) || t == typeof(ScubaManeuver?); | |
| 94 | + | |
| 95 | + public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer) | |
| 96 | + { | |
| 97 | + if (reader.TokenType == JsonToken.Null) return null; | |
| 98 | + var value = serializer.Deserialize<string>(reader); | |
| 99 | + switch (value) | |
| 100 | + { | |
| 101 | + case "ASCENT": | |
| 102 | + return ScubaManeuver.Ascent; | |
| 103 | + case "DESCENT": | |
| 104 | + return ScubaManeuver.Descent; | |
| 105 | + case "LEVEL": | |
| 106 | + return ScubaManeuver.Level; | |
| 107 | + } | |
| 108 | + throw new Exception("Cannot unmarshal type ScubaManeuver"); | |
| 109 | + } | |
| 110 | + | |
| 111 | + public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer) | |
| 112 | + { | |
| 113 | + if (untypedValue == null) | |
| 114 | + { | |
| 115 | + serializer.Serialize(writer, null); | |
| 116 | + return; | |
| 117 | + } | |
| 118 | + var value = (ScubaManeuver)untypedValue; | |
| 119 | + switch (value) | |
| 120 | + { | |
| 121 | + case ScubaManeuver.Ascent: | |
| 122 | + serializer.Serialize(writer, "ASCENT"); | |
| 123 | + return; | |
| 124 | + case ScubaManeuver.Descent: | |
| 125 | + serializer.Serialize(writer, "DESCENT"); | |
| 126 | + return; | |
| 127 | + case ScubaManeuver.Level: | |
| 128 | + serializer.Serialize(writer, "LEVEL"); | |
| 129 | + return; | |
| 130 | + } | |
| 131 | + throw new Exception("Cannot marshal type ScubaManeuver"); | |
| 132 | + } | |
| 133 | + | |
| 134 | + public static readonly ScubaManeuverConverter Singleton = new ScubaManeuverConverter(); | |
| 135 | + } | |
| 136 | +} | |
| 137 | +#pragma warning restore CS8618 | |
| 138 | +#pragma warning restore CS8601 | |
| 139 | +#pragma warning restore CS8602 | |
| 140 | +#pragma warning restore CS8603 | |
| 141 | +#pragma warning restore CS8604 | |
| 142 | +#pragma warning restore CS8625 | |
| 143 | +#pragma warning restore CS8765 |
Aschema-csharp-SystemTextJsondefault / QuickType.cs+248 −0
| @@ -0,0 +1,248 @@ | ||
| 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 | + /// <summary> | |
| 24 | + /// A SCUBA dive log with waypoints | |
| 25 | + /// </summary> | |
| 26 | + public partial class TopLevel | |
| 27 | + { | |
| 28 | + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] | |
| 29 | + [JsonPropertyName("waypoints")] | |
| 30 | + public ScubaWaypoint[]? Waypoints { get; set; } | |
| 31 | + } | |
| 32 | + | |
| 33 | + public partial class ScubaWaypoint | |
| 34 | + { | |
| 35 | + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] | |
| 36 | + [JsonPropertyName("depth")] | |
| 37 | + public double? Depth { get; set; } | |
| 38 | + | |
| 39 | + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] | |
| 40 | + [JsonPropertyName("idCard")] | |
| 41 | + public IdCardHttp? IdCard { get; set; } | |
| 42 | + | |
| 43 | + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] | |
| 44 | + [JsonPropertyName("location")] | |
| 45 | + public Point? Location { get; set; } | |
| 46 | + | |
| 47 | + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] | |
| 48 | + [JsonPropertyName("maneuver")] | |
| 49 | + public ScubaManeuver? Maneuver { get; set; } | |
| 50 | + } | |
| 51 | + | |
| 52 | + public partial class IdCardHttp | |
| 53 | + { | |
| 54 | + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] | |
| 55 | + [JsonPropertyName("value")] | |
| 56 | + public string? Value { get; set; } | |
| 57 | + } | |
| 58 | + | |
| 59 | + public partial class Point | |
| 60 | + { | |
| 61 | + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] | |
| 62 | + [JsonPropertyName("latitude")] | |
| 63 | + public double? Latitude { get; set; } | |
| 64 | + | |
| 65 | + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] | |
| 66 | + [JsonPropertyName("longitude")] | |
| 67 | + public double? Longitude { get; set; } | |
| 68 | + } | |
| 69 | + | |
| 70 | + public enum ScubaManeuver { Ascent, Descent, Level }; | |
| 71 | + | |
| 72 | + public partial class TopLevel | |
| 73 | + { | |
| 74 | + public static TopLevel FromJson(string json) => JsonSerializer.Deserialize<TopLevel>(json, QuickType.Converter.Settings); | |
| 75 | + } | |
| 76 | + | |
| 77 | + public static partial class Serialize | |
| 78 | + { | |
| 79 | + public static string ToJson(this TopLevel self) => JsonSerializer.Serialize(self, QuickType.Converter.Settings); | |
| 80 | + } | |
| 81 | + | |
| 82 | + internal static partial class Converter | |
| 83 | + { | |
| 84 | + public static readonly JsonSerializerOptions Settings = new(JsonSerializerDefaults.General) | |
| 85 | + { | |
| 86 | + Converters = | |
| 87 | + { | |
| 88 | + ScubaManeuverConverter.Singleton, | |
| 89 | + new DateOnlyConverter(), | |
| 90 | + new TimeOnlyConverter(), | |
| 91 | + IsoDateTimeOffsetConverter.Singleton | |
| 92 | + }, | |
| 93 | + }; | |
| 94 | + } | |
| 95 | + | |
| 96 | + internal class ScubaManeuverConverter : JsonConverter<ScubaManeuver> | |
| 97 | + { | |
| 98 | + public override bool CanConvert(Type t) => t == typeof(ScubaManeuver); | |
| 99 | + | |
| 100 | + public override ScubaManeuver Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
| 101 | + { | |
| 102 | + var value = reader.GetString(); | |
| 103 | + switch (value) | |
| 104 | + { | |
| 105 | + case "ASCENT": | |
| 106 | + return ScubaManeuver.Ascent; | |
| 107 | + case "DESCENT": | |
| 108 | + return ScubaManeuver.Descent; | |
| 109 | + case "LEVEL": | |
| 110 | + return ScubaManeuver.Level; | |
| 111 | + } | |
| 112 | + throw new JsonException("Cannot unmarshal type ScubaManeuver"); | |
| 113 | + } | |
| 114 | + | |
| 115 | + public override void Write(Utf8JsonWriter writer, ScubaManeuver value, JsonSerializerOptions options) | |
| 116 | + { | |
| 117 | + switch (value) | |
| 118 | + { | |
| 119 | + case ScubaManeuver.Ascent: | |
| 120 | + JsonSerializer.Serialize(writer, "ASCENT", options); | |
| 121 | + return; | |
| 122 | + case ScubaManeuver.Descent: | |
| 123 | + JsonSerializer.Serialize(writer, "DESCENT", options); | |
| 124 | + return; | |
| 125 | + case ScubaManeuver.Level: | |
| 126 | + JsonSerializer.Serialize(writer, "LEVEL", options); | |
| 127 | + return; | |
| 128 | + } | |
| 129 | + throw new NotSupportedException("Cannot marshal type ScubaManeuver"); | |
| 130 | + } | |
| 131 | + | |
| 132 | + public static readonly ScubaManeuverConverter Singleton = new ScubaManeuverConverter(); | |
| 133 | + } | |
| 134 | + | |
| 135 | + public class DateOnlyConverter : JsonConverter<DateOnly> | |
| 136 | + { | |
| 137 | + private readonly string serializationFormat; | |
| 138 | + public DateOnlyConverter() : this(null) { } | |
| 139 | + | |
| 140 | + public DateOnlyConverter(string? serializationFormat) | |
| 141 | + { | |
| 142 | + this.serializationFormat = serializationFormat ?? "yyyy-MM-dd"; | |
| 143 | + } | |
| 144 | + | |
| 145 | + public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
| 146 | + { | |
| 147 | + var value = reader.GetString(); | |
| 148 | + return DateOnly.Parse(value!); | |
| 149 | + } | |
| 150 | + | |
| 151 | + public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options) | |
| 152 | + => writer.WriteStringValue(value.ToString(serializationFormat)); | |
| 153 | + } | |
| 154 | + | |
| 155 | + public class TimeOnlyConverter : JsonConverter<TimeOnly> | |
| 156 | + { | |
| 157 | + private readonly string serializationFormat; | |
| 158 | + | |
| 159 | + public TimeOnlyConverter() : this(null) { } | |
| 160 | + | |
| 161 | + public TimeOnlyConverter(string? serializationFormat) | |
| 162 | + { | |
| 163 | + this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff"; | |
| 164 | + } | |
| 165 | + | |
| 166 | + public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
| 167 | + { | |
| 168 | + var value = reader.GetString(); | |
| 169 | + return TimeOnly.Parse(value!); | |
| 170 | + } | |
| 171 | + | |
| 172 | + public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options) | |
| 173 | + => writer.WriteStringValue(value.ToString(serializationFormat)); | |
| 174 | + } | |
| 175 | + | |
| 176 | + internal class IsoDateTimeOffsetConverter : JsonConverter<DateTimeOffset> | |
| 177 | + { | |
| 178 | + public override bool CanConvert(Type t) => t == typeof(DateTimeOffset); | |
| 179 | + | |
| 180 | + private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; | |
| 181 | + | |
| 182 | + private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind; | |
| 183 | + private string? _dateTimeFormat; | |
| 184 | + private CultureInfo? _culture; | |
| 185 | + | |
| 186 | + public DateTimeStyles DateTimeStyles | |
| 187 | + { | |
| 188 | + get => _dateTimeStyles; | |
| 189 | + set => _dateTimeStyles = value; | |
| 190 | + } | |
| 191 | + | |
| 192 | + public string? DateTimeFormat | |
| 193 | + { | |
| 194 | + get => _dateTimeFormat ?? string.Empty; | |
| 195 | + set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value; | |
| 196 | + } | |
| 197 | + | |
| 198 | + public CultureInfo Culture | |
| 199 | + { | |
| 200 | + get => _culture ?? CultureInfo.CurrentCulture; | |
| 201 | + set => _culture = value; | |
| 202 | + } | |
| 203 | + | |
| 204 | + public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options) | |
| 205 | + { | |
| 206 | + string text; | |
| 207 | + | |
| 208 | + | |
| 209 | + if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal | |
| 210 | + || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal) | |
| 211 | + { | |
| 212 | + value = value.ToUniversalTime(); | |
| 213 | + } | |
| 214 | + | |
| 215 | + text = value.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture); | |
| 216 | + | |
| 217 | + writer.WriteStringValue(text); | |
| 218 | + } | |
| 219 | + | |
| 220 | + public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
| 221 | + { | |
| 222 | + string? dateText = reader.GetString(); | |
| 223 | + | |
| 224 | + if (string.IsNullOrEmpty(dateText) == false) | |
| 225 | + { | |
| 226 | + if (!string.IsNullOrEmpty(_dateTimeFormat)) | |
| 227 | + { | |
| 228 | + return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles); | |
| 229 | + } | |
| 230 | + else | |
| 231 | + { | |
| 232 | + return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles); | |
| 233 | + } | |
| 234 | + } | |
| 235 | + else | |
| 236 | + { | |
| 237 | + return default(DateTimeOffset); | |
| 238 | + } | |
| 239 | + } | |
| 240 | + | |
| 241 | + | |
| 242 | + public static readonly IsoDateTimeOffsetConverter Singleton = new IsoDateTimeOffsetConverter(); | |
| 243 | + } | |
| 244 | +} | |
| 245 | +#pragma warning restore CS8618 | |
| 246 | +#pragma warning restore CS8601 | |
| 247 | +#pragma warning restore CS8602 | |
| 248 | +#pragma warning restore CS8603 |
Aschema-csharpdefault / QuickType.cs+143 −0
| @@ -0,0 +1,143 @@ | ||
| 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 | + /// <summary> | |
| 27 | + /// A SCUBA dive log with waypoints | |
| 28 | + /// </summary> | |
| 29 | + public partial class TopLevel | |
| 30 | + { | |
| 31 | + [JsonProperty("waypoints", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 32 | + public ScubaWaypoint[]? Waypoints { get; set; } | |
| 33 | + } | |
| 34 | + | |
| 35 | + public partial class ScubaWaypoint | |
| 36 | + { | |
| 37 | + [JsonProperty("depth", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 38 | + public double? Depth { get; set; } | |
| 39 | + | |
| 40 | + [JsonProperty("idCard", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 41 | + public IdCardHttp? IdCard { get; set; } | |
| 42 | + | |
| 43 | + [JsonProperty("location", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 44 | + public Point? Location { get; set; } | |
| 45 | + | |
| 46 | + [JsonProperty("maneuver", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 47 | + public ScubaManeuver? Maneuver { get; set; } | |
| 48 | + } | |
| 49 | + | |
| 50 | + public partial class IdCardHttp | |
| 51 | + { | |
| 52 | + [JsonProperty("value", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 53 | + public string? Value { get; set; } | |
| 54 | + } | |
| 55 | + | |
| 56 | + public partial class Point | |
| 57 | + { | |
| 58 | + [JsonProperty("latitude", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 59 | + public double? Latitude { get; set; } | |
| 60 | + | |
| 61 | + [JsonProperty("longitude", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] | |
| 62 | + public double? Longitude { get; set; } | |
| 63 | + } | |
| 64 | + | |
| 65 | + public enum ScubaManeuver { Ascent, Descent, Level }; | |
| 66 | + | |
| 67 | + public partial class TopLevel | |
| 68 | + { | |
| 69 | + public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings); | |
| 70 | + } | |
| 71 | + | |
| 72 | + public static partial class Serialize | |
| 73 | + { | |
| 74 | + public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings); | |
| 75 | + } | |
| 76 | + | |
| 77 | + internal static partial class Converter | |
| 78 | + { | |
| 79 | + public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings | |
| 80 | + { | |
| 81 | + MetadataPropertyHandling = MetadataPropertyHandling.Ignore, | |
| 82 | + DateParseHandling = DateParseHandling.None, | |
| 83 | + Converters = | |
| 84 | + { | |
| 85 | + ScubaManeuverConverter.Singleton, | |
| 86 | + new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal } | |
| 87 | + }, | |
| 88 | + }; | |
| 89 | + } | |
| 90 | + | |
| 91 | + internal class ScubaManeuverConverter : JsonConverter | |
| 92 | + { | |
| 93 | + public override bool CanConvert(Type t) => t == typeof(ScubaManeuver) || t == typeof(ScubaManeuver?); | |
| 94 | + | |
| 95 | + public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer) | |
| 96 | + { | |
| 97 | + if (reader.TokenType == JsonToken.Null) return null; | |
| 98 | + var value = serializer.Deserialize<string>(reader); | |
| 99 | + switch (value) | |
| 100 | + { | |
| 101 | + case "ASCENT": | |
| 102 | + return ScubaManeuver.Ascent; | |
| 103 | + case "DESCENT": | |
| 104 | + return ScubaManeuver.Descent; | |
| 105 | + case "LEVEL": | |
| 106 | + return ScubaManeuver.Level; | |
| 107 | + } | |
| 108 | + throw new Exception("Cannot unmarshal type ScubaManeuver"); | |
| 109 | + } | |
| 110 | + | |
| 111 | + public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer) | |
| 112 | + { | |
| 113 | + if (untypedValue == null) | |
| 114 | + { | |
| 115 | + serializer.Serialize(writer, null); | |
| 116 | + return; | |
| 117 | + } | |
| 118 | + var value = (ScubaManeuver)untypedValue; | |
| 119 | + switch (value) | |
| 120 | + { | |
| 121 | + case ScubaManeuver.Ascent: | |
| 122 | + serializer.Serialize(writer, "ASCENT"); | |
| 123 | + return; | |
| 124 | + case ScubaManeuver.Descent: | |
| 125 | + serializer.Serialize(writer, "DESCENT"); | |
| 126 | + return; | |
| 127 | + case ScubaManeuver.Level: | |
| 128 | + serializer.Serialize(writer, "LEVEL"); | |
| 129 | + return; | |
| 130 | + } | |
| 131 | + throw new Exception("Cannot marshal type ScubaManeuver"); | |
| 132 | + } | |
| 133 | + | |
| 134 | + public static readonly ScubaManeuverConverter Singleton = new ScubaManeuverConverter(); | |
| 135 | + } | |
| 136 | +} | |
| 137 | +#pragma warning restore CS8618 | |
| 138 | +#pragma warning restore CS8601 | |
| 139 | +#pragma warning restore CS8602 | |
| 140 | +#pragma warning restore CS8603 | |
| 141 | +#pragma warning restore CS8604 | |
| 142 | +#pragma warning restore CS8625 | |
| 143 | +#pragma warning restore CS8765 |
Aschema-dartdefault / TopLevel.dart+115 −0
| @@ -0,0 +1,115 @@ | ||
| 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 | + | |
| 12 | +///A SCUBA dive log with waypoints | |
| 13 | +class TopLevel { | |
| 14 | + final List<ScubaWaypoint>? waypoints; | |
| 15 | + | |
| 16 | + TopLevel({ | |
| 17 | + this.waypoints, | |
| 18 | + }); | |
| 19 | + | |
| 20 | + factory TopLevel.fromJson(Map<String, dynamic> json) => TopLevel( | |
| 21 | + waypoints: json["waypoints"] == null ? null : List<ScubaWaypoint>.from(json["waypoints"]!.map((x) => ScubaWaypoint.fromJson(x))), | |
| 22 | + ); | |
| 23 | + | |
| 24 | + Map<String, dynamic> toJson() => { | |
| 25 | + "waypoints": waypoints == null ? null : List<dynamic>.from(waypoints!.map((x) => x.toJson())), | |
| 26 | + }; | |
| 27 | +} | |
| 28 | + | |
| 29 | +class ScubaWaypoint { | |
| 30 | + final double? depth; | |
| 31 | + final IdCardHttp? idCard; | |
| 32 | + final Point? location; | |
| 33 | + final ScubaManeuver? maneuver; | |
| 34 | + | |
| 35 | + ScubaWaypoint({ | |
| 36 | + this.depth, | |
| 37 | + this.idCard, | |
| 38 | + this.location, | |
| 39 | + this.maneuver, | |
| 40 | + }); | |
| 41 | + | |
| 42 | + factory ScubaWaypoint.fromJson(Map<String, dynamic> json) => ScubaWaypoint( | |
| 43 | + depth: json["depth"]?.toDouble(), | |
| 44 | + idCard: json["idCard"] == null ? null : IdCardHttp.fromJson(json["idCard"]), | |
| 45 | + location: json["location"] == null ? null : Point.fromJson(json["location"]), | |
| 46 | + maneuver: scubaManeuverValues.map[json["maneuver"]], | |
| 47 | + ); | |
| 48 | + | |
| 49 | + Map<String, dynamic> toJson() => { | |
| 50 | + "depth": depth, | |
| 51 | + "idCard": idCard?.toJson(), | |
| 52 | + "location": location?.toJson(), | |
| 53 | + "maneuver": scubaManeuverValues.reverse[maneuver], | |
| 54 | + }; | |
| 55 | +} | |
| 56 | + | |
| 57 | +class IdCardHttp { | |
| 58 | + final String? value; | |
| 59 | + | |
| 60 | + IdCardHttp({ | |
| 61 | + this.value, | |
| 62 | + }); | |
| 63 | + | |
| 64 | + factory IdCardHttp.fromJson(Map<String, dynamic> json) => IdCardHttp( | |
| 65 | + value: json["value"], | |
| 66 | + ); | |
| 67 | + | |
| 68 | + Map<String, dynamic> toJson() => { | |
| 69 | + "value": value, | |
| 70 | + }; | |
| 71 | +} | |
| 72 | + | |
| 73 | +class Point { | |
| 74 | + final double? latitude; | |
| 75 | + final double? longitude; | |
| 76 | + | |
| 77 | + Point({ | |
| 78 | + this.latitude, | |
| 79 | + this.longitude, | |
| 80 | + }); | |
| 81 | + | |
| 82 | + factory Point.fromJson(Map<String, dynamic> json) => Point( | |
| 83 | + latitude: json["latitude"]?.toDouble(), | |
| 84 | + longitude: json["longitude"]?.toDouble(), | |
| 85 | + ); | |
| 86 | + | |
| 87 | + Map<String, dynamic> toJson() => { | |
| 88 | + "latitude": latitude, | |
| 89 | + "longitude": longitude, | |
| 90 | + }; | |
| 91 | +} | |
| 92 | + | |
| 93 | +enum ScubaManeuver { | |
| 94 | + ASCENT, | |
| 95 | + DESCENT, | |
| 96 | + LEVEL | |
| 97 | +} | |
| 98 | + | |
| 99 | +final scubaManeuverValues = EnumValues({ | |
| 100 | + "ASCENT": ScubaManeuver.ASCENT, | |
| 101 | + "DESCENT": ScubaManeuver.DESCENT, | |
| 102 | + "LEVEL": ScubaManeuver.LEVEL | |
| 103 | +}); | |
| 104 | + | |
| 105 | +class EnumValues<T> { | |
| 106 | + Map<String, T> map; | |
| 107 | + late Map<T, String> reverseMap; | |
| 108 | + | |
| 109 | + EnumValues(this.map); | |
| 110 | + | |
| 111 | + Map<T, String> get reverse { | |
| 112 | + reverseMap = map.map((k, v) => MapEntry(v, k)); | |
| 113 | + return reverseMap; | |
| 114 | + } | |
| 115 | +} |
Aschema-elixirdefault / QuickType.ex+197 −0
| @@ -0,0 +1,197 @@ | ||
| 1 | +# This file was autogenerated using quicktype https://github.com/quicktype/quicktype | |
| 2 | +# | |
| 3 | +# Add Jason to your mix.exs | |
| 4 | +# | |
| 5 | +# Decode a JSON string: TopLevel.from_json(data) | |
| 6 | +# Encode into a JSON string: TopLevel.to_json(struct) | |
| 7 | + | |
| 8 | +defmodule IDCardHTTP do | |
| 9 | + defstruct [:value] | |
| 10 | + | |
| 11 | + @type t :: %__MODULE__{ | |
| 12 | + value: String.t() | nil | |
| 13 | + } | |
| 14 | + | |
| 15 | + def from_map(m) do | |
| 16 | + %IDCardHTTP{ | |
| 17 | + value: m["value"], | |
| 18 | + } | |
| 19 | + end | |
| 20 | + | |
| 21 | + def from_json(json) do | |
| 22 | + json | |
| 23 | + |> Jason.decode!() | |
| 24 | + |> from_map() | |
| 25 | + end | |
| 26 | + | |
| 27 | + def to_map(struct) do | |
| 28 | + %{ | |
| 29 | + "value" => struct.value, | |
| 30 | + } | |
| 31 | + end | |
| 32 | + | |
| 33 | + def to_json(struct) do | |
| 34 | + struct | |
| 35 | + |> to_map() | |
| 36 | + |> Jason.encode!() | |
| 37 | + end | |
| 38 | +end | |
| 39 | + | |
| 40 | +defmodule Point do | |
| 41 | + defstruct [:latitude, :longitude] | |
| 42 | + | |
| 43 | + @type t :: %__MODULE__{ | |
| 44 | + latitude: float() | nil, | |
| 45 | + longitude: float() | nil | |
| 46 | + } | |
| 47 | + | |
| 48 | + def from_map(m) do | |
| 49 | + %Point{ | |
| 50 | + latitude: m["latitude"], | |
| 51 | + longitude: m["longitude"], | |
| 52 | + } | |
| 53 | + end | |
| 54 | + | |
| 55 | + def from_json(json) do | |
| 56 | + json | |
| 57 | + |> Jason.decode!() | |
| 58 | + |> from_map() | |
| 59 | + end | |
| 60 | + | |
| 61 | + def to_map(struct) do | |
| 62 | + %{ | |
| 63 | + "latitude" => struct.latitude, | |
| 64 | + "longitude" => struct.longitude, | |
| 65 | + } | |
| 66 | + end | |
| 67 | + | |
| 68 | + def to_json(struct) do | |
| 69 | + struct | |
| 70 | + |> to_map() | |
| 71 | + |> Jason.encode!() | |
| 72 | + end | |
| 73 | +end | |
| 74 | + | |
| 75 | +defmodule SCUBAManeuver do | |
| 76 | + @valid_enum_members [ | |
| 77 | + :ASCENT, | |
| 78 | + :DESCENT, | |
| 79 | + :LEVEL, | |
| 80 | + ] | |
| 81 | + | |
| 82 | + def valid_atom?(value), do: value in @valid_enum_members | |
| 83 | + | |
| 84 | + def valid_atom_string?(value) do | |
| 85 | + try do | |
| 86 | + atom = String.to_existing_atom(value) | |
| 87 | + atom in @valid_enum_members | |
| 88 | + rescue | |
| 89 | + ArgumentError -> false | |
| 90 | + end | |
| 91 | + end | |
| 92 | + | |
| 93 | + def encode(value) do | |
| 94 | + if valid_atom?(value) do | |
| 95 | + Atom.to_string(value) | |
| 96 | + else | |
| 97 | + {:error, "Unexpected value when encoding atom: #{inspect(value)}"} | |
| 98 | + end | |
| 99 | + end | |
| 100 | + | |
| 101 | + def decode(value) do | |
| 102 | + if valid_atom_string?(value) do | |
| 103 | + String.to_existing_atom(value) | |
| 104 | + else | |
| 105 | + {:error, "Unexpected value when decoding atom: #{inspect(value)}"} | |
| 106 | + end | |
| 107 | + end | |
| 108 | + | |
| 109 | + def from_json(json) do | |
| 110 | + json | |
| 111 | + |> Jason.decode!() | |
| 112 | + |> decode() | |
| 113 | + end | |
| 114 | + | |
| 115 | + def to_json(data) do | |
| 116 | + data | |
| 117 | + |> encode() | |
| 118 | + |> Jason.encode!() | |
| 119 | + end | |
| 120 | +end | |
| 121 | + | |
| 122 | +defmodule SCUBAWaypoint do | |
| 123 | + defstruct [:depth, :id_card, :location, :maneuver] | |
| 124 | + | |
| 125 | + @type t :: %__MODULE__{ | |
| 126 | + depth: float() | nil, | |
| 127 | + id_card: IDCardHTTP.t() | nil, | |
| 128 | + location: Point.t() | nil, | |
| 129 | + maneuver: SCUBAManeuver.t() | nil | |
| 130 | + } | |
| 131 | + | |
| 132 | + def from_map(m) do | |
| 133 | + %SCUBAWaypoint{ | |
| 134 | + depth: m["depth"], | |
| 135 | + id_card: m["idCard"] && IDCardHTTP.from_map(m["idCard"]), | |
| 136 | + location: m["location"] && Point.from_map(m["location"]), | |
| 137 | + maneuver: m["maneuver"] && SCUBAManeuver.decode(m["maneuver"]), | |
| 138 | + } | |
| 139 | + end | |
| 140 | + | |
| 141 | + def from_json(json) do | |
| 142 | + json | |
| 143 | + |> Jason.decode!() | |
| 144 | + |> from_map() | |
| 145 | + end | |
| 146 | + | |
| 147 | + def to_map(struct) do | |
| 148 | + %{ | |
| 149 | + "depth" => struct.depth, | |
| 150 | + "idCard" => struct.id_card && IDCardHTTP.to_map(struct.id_card), | |
| 151 | + "location" => struct.location && Point.to_map(struct.location), | |
| 152 | + "maneuver" => struct.maneuver && SCUBAManeuver.encode(struct.maneuver), | |
| 153 | + } | |
| 154 | + end | |
| 155 | + | |
| 156 | + def to_json(struct) do | |
| 157 | + struct | |
| 158 | + |> to_map() | |
| 159 | + |> Jason.encode!() | |
| 160 | + end | |
| 161 | +end | |
| 162 | + | |
| 163 | +defmodule TopLevel do | |
| 164 | + @moduledoc """ | |
| 165 | + A SCUBA dive log with waypoints | |
| 166 | + """ | |
| 167 | + | |
| 168 | + defstruct [:waypoints] | |
| 169 | + | |
| 170 | + @type t :: %__MODULE__{ | |
| 171 | + waypoints: [SCUBAWaypoint.t()] | nil | |
| 172 | + } | |
| 173 | + | |
| 174 | + def from_map(m) do | |
| 175 | + %TopLevel{ | |
| 176 | + waypoints: m["waypoints"] && Enum.map(m["waypoints"], &SCUBAWaypoint.from_map/1), | |
| 177 | + } | |
| 178 | + end | |
| 179 | + | |
| 180 | + def from_json(json) do | |
| 181 | + json | |
| 182 | + |> Jason.decode!() | |
| 183 | + |> from_map() | |
| 184 | + end | |
| 185 | + | |
| 186 | + def to_map(struct) do | |
| 187 | + %{ | |
| 188 | + "waypoints" => struct.waypoints && Enum.map(struct.waypoints, &SCUBAWaypoint.to_map/1), | |
| 189 | + } | |
| 190 | + end | |
| 191 | + | |
| 192 | + def to_json(struct) do | |
| 193 | + struct | |
| 194 | + |> to_map() | |
| 195 | + |> Jason.encode!() | |
| 196 | + end | |
| 197 | +end |
Aschema-elmdefault / QuickType.elm+136 −0
| @@ -0,0 +1,136 @@ | ||
| 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 | + , SCUBAWaypoint | |
| 19 | + , IDCardHTTP | |
| 20 | + , Point | |
| 21 | + , SCUBAManeuver(..) | |
| 22 | + ) | |
| 23 | + | |
| 24 | +import Json.Decode as Jdec | |
| 25 | +import Json.Decode.Pipeline as Jpipe | |
| 26 | +import Json.Encode as Jenc | |
| 27 | +import Dict exposing (Dict) | |
| 28 | + | |
| 29 | +{-| A SCUBA dive log with waypoints -} | |
| 30 | + | |
| 31 | +type alias QuickType = | |
| 32 | + { waypoints : Maybe (List SCUBAWaypoint) | |
| 33 | + } | |
| 34 | + | |
| 35 | +type alias SCUBAWaypoint = | |
| 36 | + { depth : Maybe Float | |
| 37 | + , idCard : Maybe IDCardHTTP | |
| 38 | + , location : Maybe Point | |
| 39 | + , maneuver : Maybe SCUBAManeuver | |
| 40 | + } | |
| 41 | + | |
| 42 | +type alias IDCardHTTP = | |
| 43 | + { value : Maybe String | |
| 44 | + } | |
| 45 | + | |
| 46 | +type alias Point = | |
| 47 | + { latitude : Maybe Float | |
| 48 | + , longitude : Maybe Float | |
| 49 | + } | |
| 50 | + | |
| 51 | +type SCUBAManeuver | |
| 52 | + = Ascent | |
| 53 | + | Descent | |
| 54 | + | Level | |
| 55 | + | |
| 56 | +-- decoders and encoders | |
| 57 | + | |
| 58 | +quickTypeToString : QuickType -> String | |
| 59 | +quickTypeToString r = Jenc.encode 0 (encodeQuickType r) | |
| 60 | + | |
| 61 | +quickType : Jdec.Decoder QuickType | |
| 62 | +quickType = | |
| 63 | + Jdec.succeed QuickType | |
| 64 | + |> Jpipe.optional "waypoints" (Jdec.nullable (Jdec.list scubaWaypoint)) Nothing | |
| 65 | + | |
| 66 | +encodeQuickType : QuickType -> Jenc.Value | |
| 67 | +encodeQuickType x = | |
| 68 | + Jenc.object | |
| 69 | + [ ("waypoints", makeNullableEncoder (Jenc.list encodeSCUBAWaypoint) x.waypoints) | |
| 70 | + ] | |
| 71 | + | |
| 72 | +scubaWaypoint : Jdec.Decoder SCUBAWaypoint | |
| 73 | +scubaWaypoint = | |
| 74 | + Jdec.succeed SCUBAWaypoint | |
| 75 | + |> Jpipe.optional "depth" (Jdec.nullable Jdec.float) Nothing | |
| 76 | + |> Jpipe.optional "idCard" (Jdec.nullable idCardHTTP) Nothing | |
| 77 | + |> Jpipe.optional "location" (Jdec.nullable point) Nothing | |
| 78 | + |> Jpipe.optional "maneuver" (Jdec.nullable scubaManeuver) Nothing | |
| 79 | + | |
| 80 | +encodeSCUBAWaypoint : SCUBAWaypoint -> Jenc.Value | |
| 81 | +encodeSCUBAWaypoint x = | |
| 82 | + Jenc.object | |
| 83 | + [ ("depth", makeNullableEncoder Jenc.float x.depth) | |
| 84 | + , ("idCard", makeNullableEncoder encodeIDCardHTTP x.idCard) | |
| 85 | + , ("location", makeNullableEncoder encodePoint x.location) | |
| 86 | + , ("maneuver", makeNullableEncoder encodeSCUBAManeuver x.maneuver) | |
| 87 | + ] | |
| 88 | + | |
| 89 | +idCardHTTP : Jdec.Decoder IDCardHTTP | |
| 90 | +idCardHTTP = | |
| 91 | + Jdec.succeed IDCardHTTP | |
| 92 | + |> Jpipe.optional "value" (Jdec.nullable Jdec.string) Nothing | |
| 93 | + | |
| 94 | +encodeIDCardHTTP : IDCardHTTP -> Jenc.Value | |
| 95 | +encodeIDCardHTTP x = | |
| 96 | + Jenc.object | |
| 97 | + [ ("value", makeNullableEncoder Jenc.string x.value) | |
| 98 | + ] | |
| 99 | + | |
| 100 | +point : Jdec.Decoder Point | |
| 101 | +point = | |
| 102 | + Jdec.succeed Point | |
| 103 | + |> Jpipe.optional "latitude" (Jdec.nullable Jdec.float) Nothing | |
| 104 | + |> Jpipe.optional "longitude" (Jdec.nullable Jdec.float) Nothing | |
| 105 | + | |
| 106 | +encodePoint : Point -> Jenc.Value | |
| 107 | +encodePoint x = | |
| 108 | + Jenc.object | |
| 109 | + [ ("latitude", makeNullableEncoder Jenc.float x.latitude) | |
| 110 | + , ("longitude", makeNullableEncoder Jenc.float x.longitude) | |
| 111 | + ] | |
| 112 | + | |
| 113 | +scubaManeuver : Jdec.Decoder SCUBAManeuver | |
| 114 | +scubaManeuver = | |
| 115 | + Jdec.string | |
| 116 | + |> Jdec.andThen (\str -> | |
| 117 | + case str of | |
| 118 | + "ASCENT" -> Jdec.succeed Ascent | |
| 119 | + "DESCENT" -> Jdec.succeed Descent | |
| 120 | + "LEVEL" -> Jdec.succeed Level | |
| 121 | + somethingElse -> Jdec.fail <| "Invalid SCUBAManeuver: " ++ somethingElse | |
| 122 | + ) | |
| 123 | + | |
| 124 | +encodeSCUBAManeuver : SCUBAManeuver -> Jenc.Value | |
| 125 | +encodeSCUBAManeuver x = case x of | |
| 126 | + Ascent -> Jenc.string "ASCENT" | |
| 127 | + Descent -> Jenc.string "DESCENT" | |
| 128 | + Level -> Jenc.string "LEVEL" | |
| 129 | + | |
| 130 | +--- encoder helpers | |
| 131 | + | |
| 132 | +makeNullableEncoder : (a -> Jenc.Value) -> Maybe a -> Jenc.Value | |
| 133 | +makeNullableEncoder f m = | |
| 134 | + case m of | |
| 135 | + Just x -> f x | |
| 136 | + Nothing -> Jenc.null |
Aschema-flowdefault / TopLevel.js+234 −0
| @@ -0,0 +1,234 @@ | ||
| 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 | +/** | |
| 13 | + * A SCUBA dive log with waypoints | |
| 14 | + */ | |
| 15 | +export type TopLevel = { | |
| 16 | + waypoints?: SCUBAWaypoint[]; | |
| 17 | + [property: string]: mixed; | |
| 18 | +}; | |
| 19 | + | |
| 20 | +export type SCUBAWaypoint = { | |
| 21 | + depth?: number; | |
| 22 | + idCard?: IDCardHTTP; | |
| 23 | + location?: Point; | |
| 24 | + maneuver?: SCUBAManeuver; | |
| 25 | + [property: string]: mixed; | |
| 26 | +}; | |
| 27 | + | |
| 28 | +export type IDCardHTTP = { | |
| 29 | + value?: string; | |
| 30 | + [property: string]: mixed; | |
| 31 | +}; | |
| 32 | + | |
| 33 | +export type Point = { | |
| 34 | + latitude?: number; | |
| 35 | + longitude?: number; | |
| 36 | + [property: string]: mixed; | |
| 37 | +}; | |
| 38 | + | |
| 39 | +export type SCUBAManeuver = | |
| 40 | + "ASCENT" | |
| 41 | + | "DESCENT" | |
| 42 | + | "LEVEL"; | |
| 43 | + | |
| 44 | +// Converts JSON strings to/from your types | |
| 45 | +// and asserts the results of JSON.parse at runtime | |
| 46 | +function toTopLevel(json: string): TopLevel { | |
| 47 | + return cast(JSON.parse(json), r("TopLevel")); | |
| 48 | +} | |
| 49 | + | |
| 50 | +function topLevelToJson(value: TopLevel): string { | |
| 51 | + return JSON.stringify(uncast(value, r("TopLevel")), null, 2); | |
| 52 | +} | |
| 53 | + | |
| 54 | +function invalidValue(typ: any, val: any, key: any, parent: any = '') { | |
| 55 | + const prettyTyp = prettyTypeName(typ); | |
| 56 | + const parentText = parent ? ` on ${parent}` : ''; | |
| 57 | + const keyText = key ? ` for key "${key}"` : ''; | |
| 58 | + throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`); | |
| 59 | +} | |
| 60 | + | |
| 61 | +function prettyTypeName(typ: any): string { | |
| 62 | + if (Array.isArray(typ)) { | |
| 63 | + if (typ.length === 2 && typ[0] === undefined) { | |
| 64 | + return `an optional ${prettyTypeName(typ[1])}`; | |
| 65 | + } else { | |
| 66 | + return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`; | |
| 67 | + } | |
| 68 | + } else if (typeof typ === "object" && typ.literal !== undefined) { | |
| 69 | + return typ.literal; | |
| 70 | + } else { | |
| 71 | + return typeof typ; | |
| 72 | + } | |
| 73 | +} | |
| 74 | + | |
| 75 | +function jsonToJSProps(typ: any): any { | |
| 76 | + if (typ.jsonToJS === undefined) { | |
| 77 | + const map: any = {}; | |
| 78 | + typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ }); | |
| 79 | + typ.jsonToJS = map; | |
| 80 | + } | |
| 81 | + return typ.jsonToJS; | |
| 82 | +} | |
| 83 | + | |
| 84 | +function jsToJSONProps(typ: any): any { | |
| 85 | + if (typ.jsToJSON === undefined) { | |
| 86 | + const map: any = {}; | |
| 87 | + typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ }); | |
| 88 | + typ.jsToJSON = map; | |
| 89 | + } | |
| 90 | + return typ.jsToJSON; | |
| 91 | +} | |
| 92 | + | |
| 93 | +function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any { | |
| 94 | + function transformPrimitive(typ: string, val: any): any { | |
| 95 | + if (typeof typ === typeof val) return val; | |
| 96 | + return invalidValue(typ, val, key, parent); | |
| 97 | + } | |
| 98 | + | |
| 99 | + function transformUnion(typs: any[], val: any): any { | |
| 100 | + // val must validate against one typ in typs | |
| 101 | + const l = typs.length; | |
| 102 | + for (let i = 0; i < l; i++) { | |
| 103 | + const typ = typs[i]; | |
| 104 | + try { | |
| 105 | + return transform(val, typ, getProps); | |
| 106 | + } catch (_) {} | |
| 107 | + } | |
| 108 | + return invalidValue(typs, val, key, parent); | |
| 109 | + } | |
| 110 | + | |
| 111 | + function transformEnum(cases: string[], val: any): any { | |
| 112 | + if (cases.indexOf(val) !== -1) return val; | |
| 113 | + return invalidValue(cases.map(a => { return l(a); }), val, key, parent); | |
| 114 | + } | |
| 115 | + | |
| 116 | + function transformArray(typ: any, val: any): any { | |
| 117 | + // val must be an array with no invalid elements | |
| 118 | + if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent); | |
| 119 | + return val.map(el => transform(el, typ, getProps)); | |
| 120 | + } | |
| 121 | + | |
| 122 | + function transformDate(val: any): any { | |
| 123 | + if (val === null) { | |
| 124 | + return null; | |
| 125 | + } | |
| 126 | + const d = new Date(val); | |
| 127 | + if (isNaN(d.valueOf())) { | |
| 128 | + return invalidValue(l("Date"), val, key, parent); | |
| 129 | + } | |
| 130 | + return d; | |
| 131 | + } | |
| 132 | + | |
| 133 | + function transformObject(props: { [k: string]: any }, additional: any, val: any): any { | |
| 134 | + if (val === null || typeof val !== "object" || Array.isArray(val)) { | |
| 135 | + return invalidValue(l(ref || "object"), val, key, parent); | |
| 136 | + } | |
| 137 | + const result: any = {}; | |
| 138 | + Object.getOwnPropertyNames(props).forEach(key => { | |
| 139 | + const prop = props[key]; | |
| 140 | + const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined; | |
| 141 | + result[prop.key] = transform(v, prop.typ, getProps, key, ref); | |
| 142 | + }); | |
| 143 | + Object.getOwnPropertyNames(val).forEach(key => { | |
| 144 | + if (!Object.prototype.hasOwnProperty.call(props, key)) { | |
| 145 | + result[key] = transform(val[key], additional, getProps, key, ref); | |
| 146 | + } | |
| 147 | + }); | |
| 148 | + return result; | |
| 149 | + } | |
| 150 | + | |
| 151 | + if (typ === "any") return val; | |
| 152 | + if (typ === null) { | |
| 153 | + if (val === null) return val; | |
| 154 | + return invalidValue(typ, val, key, parent); | |
| 155 | + } | |
| 156 | + if (typ === false) return invalidValue(typ, val, key, parent); | |
| 157 | + let ref: any = undefined; | |
| 158 | + while (typeof typ === "object" && typ.ref !== undefined) { | |
| 159 | + ref = typ.ref; | |
| 160 | + typ = typeMap[typ.ref]; | |
| 161 | + } | |
| 162 | + if (Array.isArray(typ)) return transformEnum(typ, val); | |
| 163 | + if (typeof typ === "object") { | |
| 164 | + return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val) | |
| 165 | + : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val) | |
| 166 | + : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val) | |
| 167 | + : invalidValue(typ, val, key, parent); | |
| 168 | + } | |
| 169 | + // Numbers can be parsed by Date but shouldn't be. | |
| 170 | + if (typ === Date && typeof val !== "number") return transformDate(val); | |
| 171 | + return transformPrimitive(typ, val); | |
| 172 | +} | |
| 173 | + | |
| 174 | +function cast<T>(val: any, typ: any): T { | |
| 175 | + return transform(val, typ, jsonToJSProps); | |
| 176 | +} | |
| 177 | + | |
| 178 | +function uncast<T>(val: T, typ: any): any { | |
| 179 | + return transform(val, typ, jsToJSONProps); | |
| 180 | +} | |
| 181 | + | |
| 182 | +function l(typ: any) { | |
| 183 | + return { literal: typ }; | |
| 184 | +} | |
| 185 | + | |
| 186 | +function a(typ: any) { | |
| 187 | + return { arrayItems: typ }; | |
| 188 | +} | |
| 189 | + | |
| 190 | +function u(...typs: any[]) { | |
| 191 | + return { unionMembers: typs }; | |
| 192 | +} | |
| 193 | + | |
| 194 | +function o(props: any[], additional: any) { | |
| 195 | + return { props, additional }; | |
| 196 | +} | |
| 197 | + | |
| 198 | +function m(additional: any) { | |
| 199 | + const props: any[] = []; | |
| 200 | + return { props, additional }; | |
| 201 | +} | |
| 202 | + | |
| 203 | +function r(name: string) { | |
| 204 | + return { ref: name }; | |
| 205 | +} | |
| 206 | + | |
| 207 | +const typeMap: any = { | |
| 208 | + "TopLevel": o([ | |
| 209 | + { json: "waypoints", js: "waypoints", typ: u(undefined, a(r("SCUBAWaypoint"))) }, | |
| 210 | + ], "any"), | |
| 211 | + "SCUBAWaypoint": o([ | |
| 212 | + { json: "depth", js: "depth", typ: u(undefined, 3.14) }, | |
| 213 | + { json: "idCard", js: "idCard", typ: u(undefined, r("IDCardHTTP")) }, | |
| 214 | + { json: "location", js: "location", typ: u(undefined, r("Point")) }, | |
| 215 | + { json: "maneuver", js: "maneuver", typ: u(undefined, r("SCUBAManeuver")) }, | |
| 216 | + ], "any"), | |
| 217 | + "IDCardHTTP": o([ | |
| 218 | + { json: "value", js: "value", typ: u(undefined, "") }, | |
| 219 | + ], "any"), | |
| 220 | + "Point": o([ | |
| 221 | + { json: "latitude", js: "latitude", typ: u(undefined, 3.14) }, | |
| 222 | + { json: "longitude", js: "longitude", typ: u(undefined, 3.14) }, | |
| 223 | + ], "any"), | |
| 224 | + "SCUBAManeuver": [ | |
| 225 | + "ASCENT", | |
| 226 | + "DESCENT", | |
| 227 | + "LEVEL", | |
| 228 | + ], | |
| 229 | +}; | |
| 230 | + | |
| 231 | +module.exports = { | |
| 232 | + "topLevelToJson": topLevelToJson, | |
| 233 | + "toTopLevel": toTopLevel, | |
| 234 | +}; |
Aschema-golangdefault / quicktype.go+48 −0
| @@ -0,0 +1,48 @@ | ||
| 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 | +// A SCUBA dive log with waypoints | |
| 22 | +type TopLevel struct { | |
| 23 | + Waypoints []SCUBAWaypoint `json:"waypoints,omitempty"` | |
| 24 | +} | |
| 25 | + | |
| 26 | +type SCUBAWaypoint struct { | |
| 27 | + Depth *float64 `json:"depth,omitempty"` | |
| 28 | + IDCard *IDCardHTTP `json:"idCard,omitempty"` | |
| 29 | + Location *Point `json:"location,omitempty"` | |
| 30 | + Maneuver *SCUBAManeuver `json:"maneuver,omitempty"` | |
| 31 | +} | |
| 32 | + | |
| 33 | +type IDCardHTTP struct { | |
| 34 | + Value *string `json:"value,omitempty"` | |
| 35 | +} | |
| 36 | + | |
| 37 | +type Point struct { | |
| 38 | + Latitude *float64 `json:"latitude,omitempty"` | |
| 39 | + Longitude *float64 `json:"longitude,omitempty"` | |
| 40 | +} | |
| 41 | + | |
| 42 | +type SCUBAManeuver string | |
| 43 | + | |
| 44 | +const ( | |
| 45 | + Ascent SCUBAManeuver = "ASCENT" | |
| 46 | + Descent SCUBAManeuver = "DESCENT" | |
| 47 | + Level SCUBAManeuver = "LEVEL" | |
| 48 | +) |
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 / IDCardHTTP.java+12 −0
| @@ -0,0 +1,12 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | + | |
| 5 | +public class IDCardHTTP { | |
| 6 | + private String value; | |
| 7 | + | |
| 8 | + @JsonProperty("value") | |
| 9 | + public String getValue() { return value; } | |
| 10 | + @JsonProperty("value") | |
| 11 | + public void setValue(String value) { this.value = value; } | |
| 12 | +} |
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / Point.java+18 −0
| @@ -0,0 +1,18 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | + | |
| 5 | +public class Point { | |
| 6 | + private Double latitude; | |
| 7 | + private Double longitude; | |
| 8 | + | |
| 9 | + @JsonProperty("latitude") | |
| 10 | + public Double getLatitude() { return latitude; } | |
| 11 | + @JsonProperty("latitude") | |
| 12 | + public void setLatitude(Double value) { this.latitude = value; } | |
| 13 | + | |
| 14 | + @JsonProperty("longitude") | |
| 15 | + public Double getLongitude() { return longitude; } | |
| 16 | + @JsonProperty("longitude") | |
| 17 | + public void setLongitude(Double value) { this.longitude = value; } | |
| 18 | +} |
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / SCUBAManeuver.java+26 −0
| @@ -0,0 +1,26 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import java.io.IOException; | |
| 4 | +import com.fasterxml.jackson.annotation.*; | |
| 5 | + | |
| 6 | +public enum SCUBAManeuver { | |
| 7 | + ASCENT, DESCENT, LEVEL; | |
| 8 | + | |
| 9 | + @JsonValue | |
| 10 | + public String toValue() { | |
| 11 | + switch (this) { | |
| 12 | + case ASCENT: return "ASCENT"; | |
| 13 | + case DESCENT: return "DESCENT"; | |
| 14 | + case LEVEL: return "LEVEL"; | |
| 15 | + } | |
| 16 | + return null; | |
| 17 | + } | |
| 18 | + | |
| 19 | + @JsonCreator | |
| 20 | + public static SCUBAManeuver forValue(String value) throws IOException { | |
| 21 | + if (value.equals("ASCENT")) return ASCENT; | |
| 22 | + if (value.equals("DESCENT")) return DESCENT; | |
| 23 | + if (value.equals("LEVEL")) return LEVEL; | |
| 24 | + throw new IOException("Cannot deserialize SCUBAManeuver"); | |
| 25 | + } | |
| 26 | +} |
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / SCUBAWaypoint.java+30 −0
| @@ -0,0 +1,30 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | + | |
| 5 | +public class SCUBAWaypoint { | |
| 6 | + private Double depth; | |
| 7 | + private IDCardHTTP idCard; | |
| 8 | + private Point location; | |
| 9 | + private SCUBAManeuver maneuver; | |
| 10 | + | |
| 11 | + @JsonProperty("depth") | |
| 12 | + public Double getDepth() { return depth; } | |
| 13 | + @JsonProperty("depth") | |
| 14 | + public void setDepth(Double value) { this.depth = value; } | |
| 15 | + | |
| 16 | + @JsonProperty("idCard") | |
| 17 | + public IDCardHTTP getIDCard() { return idCard; } | |
| 18 | + @JsonProperty("idCard") | |
| 19 | + public void setIDCard(IDCardHTTP value) { this.idCard = value; } | |
| 20 | + | |
| 21 | + @JsonProperty("location") | |
| 22 | + public Point getLocation() { return location; } | |
| 23 | + @JsonProperty("location") | |
| 24 | + public void setLocation(Point value) { this.location = value; } | |
| 25 | + | |
| 26 | + @JsonProperty("maneuver") | |
| 27 | + public SCUBAManeuver getManeuver() { return maneuver; } | |
| 28 | + @JsonProperty("maneuver") | |
| 29 | + public void setManeuver(SCUBAManeuver value) { this.maneuver = value; } | |
| 30 | +} |
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / TopLevel.java+16 −0
| @@ -0,0 +1,16 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | +import java.util.List; | |
| 5 | + | |
| 6 | +/** | |
| 7 | + * A SCUBA dive log with waypoints | |
| 8 | + */ | |
| 9 | +public class TopLevel { | |
| 10 | + private List<SCUBAWaypoint> waypoints; | |
| 11 | + | |
| 12 | + @JsonProperty("waypoints") | |
| 13 | + public List<SCUBAWaypoint> getWaypoints() { return waypoints; } | |
| 14 | + @JsonProperty("waypoints") | |
| 15 | + public void setWaypoints(List<SCUBAWaypoint> value) { this.waypoints = value; } | |
| 16 | +} |
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 / IDCardHTTP.java+12 −0
| @@ -0,0 +1,12 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | + | |
| 5 | +public class IDCardHTTP { | |
| 6 | + private String value; | |
| 7 | + | |
| 8 | + @JsonProperty("value") | |
| 9 | + public String getValue() { return value; } | |
| 10 | + @JsonProperty("value") | |
| 11 | + public void setValue(String value) { this.value = value; } | |
| 12 | +} |
Aschema-java-lombokdefault / src / main / java / io / quicktype / Point.java+18 −0
| @@ -0,0 +1,18 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | + | |
| 5 | +public class Point { | |
| 6 | + private Double latitude; | |
| 7 | + private Double longitude; | |
| 8 | + | |
| 9 | + @JsonProperty("latitude") | |
| 10 | + public Double getLatitude() { return latitude; } | |
| 11 | + @JsonProperty("latitude") | |
| 12 | + public void setLatitude(Double value) { this.latitude = value; } | |
| 13 | + | |
| 14 | + @JsonProperty("longitude") | |
| 15 | + public Double getLongitude() { return longitude; } | |
| 16 | + @JsonProperty("longitude") | |
| 17 | + public void setLongitude(Double value) { this.longitude = value; } | |
| 18 | +} |
Aschema-java-lombokdefault / src / main / java / io / quicktype / SCUBAManeuver.java+26 −0
| @@ -0,0 +1,26 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import java.io.IOException; | |
| 4 | +import com.fasterxml.jackson.annotation.*; | |
| 5 | + | |
| 6 | +public enum SCUBAManeuver { | |
| 7 | + ASCENT, DESCENT, LEVEL; | |
| 8 | + | |
| 9 | + @JsonValue | |
| 10 | + public String toValue() { | |
| 11 | + switch (this) { | |
| 12 | + case ASCENT: return "ASCENT"; | |
| 13 | + case DESCENT: return "DESCENT"; | |
| 14 | + case LEVEL: return "LEVEL"; | |
| 15 | + } | |
| 16 | + return null; | |
| 17 | + } | |
| 18 | + | |
| 19 | + @JsonCreator | |
| 20 | + public static SCUBAManeuver forValue(String value) throws IOException { | |
| 21 | + if (value.equals("ASCENT")) return ASCENT; | |
| 22 | + if (value.equals("DESCENT")) return DESCENT; | |
| 23 | + if (value.equals("LEVEL")) return LEVEL; | |
| 24 | + throw new IOException("Cannot deserialize SCUBAManeuver"); | |
| 25 | + } | |
| 26 | +} |
Aschema-java-lombokdefault / src / main / java / io / quicktype / SCUBAWaypoint.java+30 −0
| @@ -0,0 +1,30 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | + | |
| 5 | +public class SCUBAWaypoint { | |
| 6 | + private Double depth; | |
| 7 | + private IDCardHTTP idCard; | |
| 8 | + private Point location; | |
| 9 | + private SCUBAManeuver maneuver; | |
| 10 | + | |
| 11 | + @JsonProperty("depth") | |
| 12 | + public Double getDepth() { return depth; } | |
| 13 | + @JsonProperty("depth") | |
| 14 | + public void setDepth(Double value) { this.depth = value; } | |
| 15 | + | |
| 16 | + @JsonProperty("idCard") | |
| 17 | + public IDCardHTTP getIDCard() { return idCard; } | |
| 18 | + @JsonProperty("idCard") | |
| 19 | + public void setIDCard(IDCardHTTP value) { this.idCard = value; } | |
| 20 | + | |
| 21 | + @JsonProperty("location") | |
| 22 | + public Point getLocation() { return location; } | |
| 23 | + @JsonProperty("location") | |
| 24 | + public void setLocation(Point value) { this.location = value; } | |
| 25 | + | |
| 26 | + @JsonProperty("maneuver") | |
| 27 | + public SCUBAManeuver getManeuver() { return maneuver; } | |
| 28 | + @JsonProperty("maneuver") | |
| 29 | + public void setManeuver(SCUBAManeuver value) { this.maneuver = value; } | |
| 30 | +} |
Aschema-java-lombokdefault / src / main / java / io / quicktype / TopLevel.java+16 −0
| @@ -0,0 +1,16 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | +import java.util.List; | |
| 5 | + | |
| 6 | +/** | |
| 7 | + * A SCUBA dive log with waypoints | |
| 8 | + */ | |
| 9 | +public class TopLevel { | |
| 10 | + private List<SCUBAWaypoint> waypoints; | |
| 11 | + | |
| 12 | + @JsonProperty("waypoints") | |
| 13 | + public List<SCUBAWaypoint> getWaypoints() { return waypoints; } | |
| 14 | + @JsonProperty("waypoints") | |
| 15 | + public void setWaypoints(List<SCUBAWaypoint> value) { this.waypoints = value; } | |
| 16 | +} |
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 / IDCardHTTP.java+12 −0
| @@ -0,0 +1,12 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | + | |
| 5 | +public class IDCardHTTP { | |
| 6 | + private String value; | |
| 7 | + | |
| 8 | + @JsonProperty("value") | |
| 9 | + public String getValue() { return value; } | |
| 10 | + @JsonProperty("value") | |
| 11 | + public void setValue(String value) { this.value = value; } | |
| 12 | +} |
Aschema-javadefault / src / main / java / io / quicktype / Point.java+18 −0
| @@ -0,0 +1,18 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | + | |
| 5 | +public class Point { | |
| 6 | + private Double latitude; | |
| 7 | + private Double longitude; | |
| 8 | + | |
| 9 | + @JsonProperty("latitude") | |
| 10 | + public Double getLatitude() { return latitude; } | |
| 11 | + @JsonProperty("latitude") | |
| 12 | + public void setLatitude(Double value) { this.latitude = value; } | |
| 13 | + | |
| 14 | + @JsonProperty("longitude") | |
| 15 | + public Double getLongitude() { return longitude; } | |
| 16 | + @JsonProperty("longitude") | |
| 17 | + public void setLongitude(Double value) { this.longitude = value; } | |
| 18 | +} |
Aschema-javadefault / src / main / java / io / quicktype / SCUBAManeuver.java+26 −0
| @@ -0,0 +1,26 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import java.io.IOException; | |
| 4 | +import com.fasterxml.jackson.annotation.*; | |
| 5 | + | |
| 6 | +public enum SCUBAManeuver { | |
| 7 | + ASCENT, DESCENT, LEVEL; | |
| 8 | + | |
| 9 | + @JsonValue | |
| 10 | + public String toValue() { | |
| 11 | + switch (this) { | |
| 12 | + case ASCENT: return "ASCENT"; | |
| 13 | + case DESCENT: return "DESCENT"; | |
| 14 | + case LEVEL: return "LEVEL"; | |
| 15 | + } | |
| 16 | + return null; | |
| 17 | + } | |
| 18 | + | |
| 19 | + @JsonCreator | |
| 20 | + public static SCUBAManeuver forValue(String value) throws IOException { | |
| 21 | + if (value.equals("ASCENT")) return ASCENT; | |
| 22 | + if (value.equals("DESCENT")) return DESCENT; | |
| 23 | + if (value.equals("LEVEL")) return LEVEL; | |
| 24 | + throw new IOException("Cannot deserialize SCUBAManeuver"); | |
| 25 | + } | |
| 26 | +} |
Aschema-javadefault / src / main / java / io / quicktype / SCUBAWaypoint.java+30 −0
| @@ -0,0 +1,30 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | + | |
| 5 | +public class SCUBAWaypoint { | |
| 6 | + private Double depth; | |
| 7 | + private IDCardHTTP idCard; | |
| 8 | + private Point location; | |
| 9 | + private SCUBAManeuver maneuver; | |
| 10 | + | |
| 11 | + @JsonProperty("depth") | |
| 12 | + public Double getDepth() { return depth; } | |
| 13 | + @JsonProperty("depth") | |
| 14 | + public void setDepth(Double value) { this.depth = value; } | |
| 15 | + | |
| 16 | + @JsonProperty("idCard") | |
| 17 | + public IDCardHTTP getIDCard() { return idCard; } | |
| 18 | + @JsonProperty("idCard") | |
| 19 | + public void setIDCard(IDCardHTTP value) { this.idCard = value; } | |
| 20 | + | |
| 21 | + @JsonProperty("location") | |
| 22 | + public Point getLocation() { return location; } | |
| 23 | + @JsonProperty("location") | |
| 24 | + public void setLocation(Point value) { this.location = value; } | |
| 25 | + | |
| 26 | + @JsonProperty("maneuver") | |
| 27 | + public SCUBAManeuver getManeuver() { return maneuver; } | |
| 28 | + @JsonProperty("maneuver") | |
| 29 | + public void setManeuver(SCUBAManeuver value) { this.maneuver = value; } | |
| 30 | +} |
Aschema-javadefault / src / main / java / io / quicktype / TopLevel.java+16 −0
| @@ -0,0 +1,16 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +import com.fasterxml.jackson.annotation.*; | |
| 4 | +import java.util.List; | |
| 5 | + | |
| 6 | +/** | |
| 7 | + * A SCUBA dive log with waypoints | |
| 8 | + */ | |
| 9 | +public class TopLevel { | |
| 10 | + private List<SCUBAWaypoint> waypoints; | |
| 11 | + | |
| 12 | + @JsonProperty("waypoints") | |
| 13 | + public List<SCUBAWaypoint> getWaypoints() { return waypoints; } | |
| 14 | + @JsonProperty("waypoints") | |
| 15 | + public void setWaypoints(List<SCUBAWaypoint> value) { this.waypoints = value; } | |
| 16 | +} |
Aschema-javascriptdefault / TopLevel.js+200 −0
| @@ -0,0 +1,200 @@ | ||
| 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: "waypoints", js: "waypoints", typ: u(undefined, a(r("SCUBAWaypoint"))) }, | |
| 176 | + ], "any"), | |
| 177 | + "SCUBAWaypoint": o([ | |
| 178 | + { json: "depth", js: "depth", typ: u(undefined, 3.14) }, | |
| 179 | + { json: "idCard", js: "idCard", typ: u(undefined, r("IDCardHTTP")) }, | |
| 180 | + { json: "location", js: "location", typ: u(undefined, r("Point")) }, | |
| 181 | + { json: "maneuver", js: "maneuver", typ: u(undefined, r("SCUBAManeuver")) }, | |
| 182 | + ], "any"), | |
| 183 | + "IDCardHTTP": o([ | |
| 184 | + { json: "value", js: "value", typ: u(undefined, "") }, | |
| 185 | + ], "any"), | |
| 186 | + "Point": o([ | |
| 187 | + { json: "latitude", js: "latitude", typ: u(undefined, 3.14) }, | |
| 188 | + { json: "longitude", js: "longitude", typ: u(undefined, 3.14) }, | |
| 189 | + ], "any"), | |
| 190 | + "SCUBAManeuver": [ | |
| 191 | + "ASCENT", | |
| 192 | + "DESCENT", | |
| 193 | + "LEVEL", | |
| 194 | + ], | |
| 195 | +}; | |
| 196 | + | |
| 197 | +module.exports = { | |
| 198 | + "topLevelToJson": topLevelToJson, | |
| 199 | + "toTopLevel": toTopLevel, | |
| 200 | +}; |
Aschema-kotlin-jacksondefault / TopLevel.kt+75 −0
| @@ -0,0 +1,75 @@ | ||
| 1 | +// To parse the JSON, install jackson-module-kotlin and do: | |
| 2 | +// | |
| 3 | +// val topLevel = TopLevel.fromJson(jsonString) | |
| 4 | + | |
| 5 | +package quicktype | |
| 6 | + | |
| 7 | +import com.fasterxml.jackson.annotation.* | |
| 8 | +import com.fasterxml.jackson.core.* | |
| 9 | +import com.fasterxml.jackson.databind.* | |
| 10 | +import com.fasterxml.jackson.databind.deser.std.StdDeserializer | |
| 11 | +import com.fasterxml.jackson.databind.module.SimpleModule | |
| 12 | +import com.fasterxml.jackson.databind.node.* | |
| 13 | +import com.fasterxml.jackson.databind.ser.std.StdSerializer | |
| 14 | +import com.fasterxml.jackson.module.kotlin.* | |
| 15 | + | |
| 16 | + | |
| 17 | +@Suppress("UNCHECKED_CAST") | |
| 18 | +private fun <T> ObjectMapper.convert(k: kotlin.reflect.KClass<*>, fromJson: (JsonNode) -> T, toJson: (T) -> String, isUnion: Boolean = false) = registerModule(SimpleModule().apply { | |
| 19 | + addSerializer(k.java as Class<T>, object : StdSerializer<T>(k.java as Class<T>) { | |
| 20 | + override fun serialize(value: T, gen: JsonGenerator, provider: SerializerProvider) = gen.writeRawValue(toJson(value)) | |
| 21 | + }) | |
| 22 | + addDeserializer(k.java as Class<T>, object : StdDeserializer<T>(k.java as Class<T>) { | |
| 23 | + override fun deserialize(p: JsonParser, ctxt: DeserializationContext) = fromJson(p.readValueAsTree()) | |
| 24 | + }) | |
| 25 | +}) | |
| 26 | + | |
| 27 | +val mapper = jacksonObjectMapper().apply { | |
| 28 | + propertyNamingStrategy = PropertyNamingStrategy.LOWER_CAMEL_CASE | |
| 29 | + setSerializationInclusion(JsonInclude.Include.NON_NULL) | |
| 30 | + convert(SCUBAManeuver::class, { SCUBAManeuver.fromValue(it.asText()) }, { "\"${it.value}\"" }) | |
| 31 | +} | |
| 32 | + | |
| 33 | +/** | |
| 34 | + * A SCUBA dive log with waypoints | |
| 35 | + */ | |
| 36 | +data class TopLevel ( | |
| 37 | + val waypoints: List<SCUBAWaypoint>? = null | |
| 38 | +) { | |
| 39 | + fun toJson() = mapper.writeValueAsString(this) | |
| 40 | + | |
| 41 | + companion object { | |
| 42 | + fun fromJson(json: String) = mapper.readValue<TopLevel>(json) | |
| 43 | + } | |
| 44 | +} | |
| 45 | + | |
| 46 | +data class SCUBAWaypoint ( | |
| 47 | + val depth: Double? = null, | |
| 48 | + val idCard: IDCardHTTP? = null, | |
| 49 | + val location: Point? = null, | |
| 50 | + val maneuver: SCUBAManeuver? = null | |
| 51 | +) | |
| 52 | + | |
| 53 | +data class IDCardHTTP ( | |
| 54 | + val value: String? = null | |
| 55 | +) | |
| 56 | + | |
| 57 | +data class Point ( | |
| 58 | + val latitude: Double? = null, | |
| 59 | + val longitude: Double? = null | |
| 60 | +) | |
| 61 | + | |
| 62 | +enum class SCUBAManeuver(val value: String) { | |
| 63 | + Ascent("ASCENT"), | |
| 64 | + Descent("DESCENT"), | |
| 65 | + Level("LEVEL"); | |
| 66 | + | |
| 67 | + companion object { | |
| 68 | + fun fromValue(value: String): SCUBAManeuver = when (value) { | |
| 69 | + "ASCENT" -> Ascent | |
| 70 | + "DESCENT" -> Descent | |
| 71 | + "LEVEL" -> Level | |
| 72 | + else -> throw IllegalArgumentException() | |
| 73 | + } | |
| 74 | + } | |
| 75 | +} |
Aschema-kotlindefault / TopLevel.kt+62 −0
| @@ -0,0 +1,62 @@ | ||
| 1 | +// To parse the JSON, install Klaxon and do: | |
| 2 | +// | |
| 3 | +// val topLevel = TopLevel.fromJson(jsonString) | |
| 4 | + | |
| 5 | +package quicktype | |
| 6 | + | |
| 7 | +import com.beust.klaxon.* | |
| 8 | + | |
| 9 | +private fun <T> Klaxon.convert(k: kotlin.reflect.KClass<*>, fromJson: (JsonValue) -> T, toJson: (T) -> String, isUnion: Boolean = false) = | |
| 10 | + this.converter(object: Converter { | |
| 11 | + @Suppress("UNCHECKED_CAST") | |
| 12 | + override fun toJson(value: Any) = toJson(value as T) | |
| 13 | + override fun fromJson(jv: JsonValue) = fromJson(jv) as Any | |
| 14 | + override fun canConvert(cls: Class<*>) = cls == k.java || (isUnion && cls.superclass == k.java) | |
| 15 | + }) | |
| 16 | + | |
| 17 | +private val klaxon = Klaxon() | |
| 18 | + .convert(SCUBAManeuver::class, { SCUBAManeuver.fromValue(it.string!!) }, { "\"${it.value}\"" }) | |
| 19 | + | |
| 20 | +/** | |
| 21 | + * A SCUBA dive log with waypoints | |
| 22 | + */ | |
| 23 | +data class TopLevel ( | |
| 24 | + val waypoints: List<SCUBAWaypoint>? = null | |
| 25 | +) { | |
| 26 | + public fun toJson() = klaxon.toJsonString(this) | |
| 27 | + | |
| 28 | + companion object { | |
| 29 | + public fun fromJson(json: String) = klaxon.parse<TopLevel>(json) | |
| 30 | + } | |
| 31 | +} | |
| 32 | + | |
| 33 | +data class SCUBAWaypoint ( | |
| 34 | + val depth: Double? = null, | |
| 35 | + val idCard: IDCardHTTP? = null, | |
| 36 | + val location: Point? = null, | |
| 37 | + val maneuver: SCUBAManeuver? = null | |
| 38 | +) | |
| 39 | + | |
| 40 | +data class IDCardHTTP ( | |
| 41 | + val value: String? = null | |
| 42 | +) | |
| 43 | + | |
| 44 | +data class Point ( | |
| 45 | + val latitude: Double? = null, | |
| 46 | + val longitude: Double? = null | |
| 47 | +) | |
| 48 | + | |
| 49 | +enum class SCUBAManeuver(val value: String) { | |
| 50 | + Ascent("ASCENT"), | |
| 51 | + Descent("DESCENT"), | |
| 52 | + Level("LEVEL"); | |
| 53 | + | |
| 54 | + companion object { | |
| 55 | + public fun fromValue(value: String): SCUBAManeuver = when (value) { | |
| 56 | + "ASCENT" -> Ascent | |
| 57 | + "DESCENT" -> Descent | |
| 58 | + "LEVEL" -> Level | |
| 59 | + else -> throw IllegalArgumentException() | |
| 60 | + } | |
| 61 | + } | |
| 62 | +} |
Aschema-kotlinxdefault / TopLevel.kt+45 −0
| @@ -0,0 +1,45 @@ | ||
| 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 | +/** | |
| 14 | + * A SCUBA dive log with waypoints | |
| 15 | + */ | |
| 16 | +@Serializable | |
| 17 | +data class TopLevel ( | |
| 18 | + val waypoints: List<SCUBAWaypoint>? = null | |
| 19 | +) | |
| 20 | + | |
| 21 | +@Serializable | |
| 22 | +data class SCUBAWaypoint ( | |
| 23 | + val depth: Double? = null, | |
| 24 | + val idCard: IDCardHTTP? = null, | |
| 25 | + val location: Point? = null, | |
| 26 | + val maneuver: SCUBAManeuver? = null | |
| 27 | +) | |
| 28 | + | |
| 29 | +@Serializable | |
| 30 | +data class IDCardHTTP ( | |
| 31 | + val value: String? = null | |
| 32 | +) | |
| 33 | + | |
| 34 | +@Serializable | |
| 35 | +data class Point ( | |
| 36 | + val latitude: Double? = null, | |
| 37 | + val longitude: Double? = null | |
| 38 | +) | |
| 39 | + | |
| 40 | +@Serializable | |
| 41 | +enum class SCUBAManeuver(val value: String) { | |
| 42 | + @SerialName("ASCENT") Ascent("ASCENT"), | |
| 43 | + @SerialName("DESCENT") Descent("DESCENT"), | |
| 44 | + @SerialName("LEVEL") Level("LEVEL"); | |
| 45 | +} |
Aschema-phpdefault / TopLevel.php+758 −0
| @@ -0,0 +1,758 @@ | ||
| 1 | +<?php | |
| 2 | +declare(strict_types=1); | |
| 3 | + | |
| 4 | +// This is an autogenerated file:TopLevel | |
| 5 | + | |
| 6 | +class TopLevel { | |
| 7 | + private ?array $waypoints; // json:waypoints Optional | |
| 8 | + | |
| 9 | + /** | |
| 10 | + * @param array|null $waypoints | |
| 11 | + */ | |
| 12 | + public function __construct(?array $waypoints) { | |
| 13 | + $this->waypoints = $waypoints; | |
| 14 | + } | |
| 15 | + | |
| 16 | + /** | |
| 17 | + * @param ?array $value | |
| 18 | + * @throws Exception | |
| 19 | + * @return ?array | |
| 20 | + */ | |
| 21 | + public static function fromWaypoints(?array $value): ?array { | |
| 22 | + if (!is_null($value)) { | |
| 23 | + return array_map(function ($value) { | |
| 24 | + return SCUBAWaypoint::from($value); /*class*/ | |
| 25 | + }, $value); | |
| 26 | + } else { | |
| 27 | + return null; | |
| 28 | + } | |
| 29 | + } | |
| 30 | + | |
| 31 | + /** | |
| 32 | + * @throws Exception | |
| 33 | + * @return ?array | |
| 34 | + */ | |
| 35 | + public function toWaypoints(): ?array { | |
| 36 | + if (TopLevel::validateWaypoints($this->waypoints)) { | |
| 37 | + if (!is_null($this->waypoints)) { | |
| 38 | + return array_map(function ($value) { | |
| 39 | + return $value->to(); /*class*/ | |
| 40 | + }, $this->waypoints); | |
| 41 | + } else { | |
| 42 | + return null; | |
| 43 | + } | |
| 44 | + } | |
| 45 | + throw new Exception('never get to this TopLevel::waypoints'); | |
| 46 | + } | |
| 47 | + | |
| 48 | + /** | |
| 49 | + * @param array|null | |
| 50 | + * @return bool | |
| 51 | + * @throws Exception | |
| 52 | + */ | |
| 53 | + public static function validateWaypoints(?array $value): bool { | |
| 54 | + if (!is_null($value)) { | |
| 55 | + if (!is_array($value)) { | |
| 56 | + throw new Exception("Attribute Error:TopLevel::waypoints"); | |
| 57 | + } | |
| 58 | + array_walk($value, function($value_v) { | |
| 59 | + $value_v->validate(); | |
| 60 | + }); | |
| 61 | + } | |
| 62 | + return true; | |
| 63 | + } | |
| 64 | + | |
| 65 | + /** | |
| 66 | + * @throws Exception | |
| 67 | + * @return ?array | |
| 68 | + */ | |
| 69 | + public function getWaypoints(): ?array { | |
| 70 | + if (TopLevel::validateWaypoints($this->waypoints)) { | |
| 71 | + return $this->waypoints; | |
| 72 | + } | |
| 73 | + throw new Exception('never get to getWaypoints TopLevel::waypoints'); | |
| 74 | + } | |
| 75 | + | |
| 76 | + /** | |
| 77 | + * @return ?array | |
| 78 | + */ | |
| 79 | + public static function sampleWaypoints(): ?array { | |
| 80 | + return array( | |
| 81 | + SCUBAWaypoint::sample() /*31:*/ | |
| 82 | + ); /* 31:waypoints*/ | |
| 83 | + } | |
| 84 | + | |
| 85 | + /** | |
| 86 | + * @throws Exception | |
| 87 | + * @return bool | |
| 88 | + */ | |
| 89 | + public function validate(): bool { | |
| 90 | + return TopLevel::validateWaypoints($this->waypoints); | |
| 91 | + } | |
| 92 | + | |
| 93 | + /** | |
| 94 | + * @return stdClass | |
| 95 | + * @throws Exception | |
| 96 | + */ | |
| 97 | + public function to(): stdClass { | |
| 98 | + $out = new stdClass(); | |
| 99 | + $out->{'waypoints'} = $this->toWaypoints(); | |
| 100 | + return $out; | |
| 101 | + } | |
| 102 | + | |
| 103 | + /** | |
| 104 | + * @param stdClass $obj | |
| 105 | + * @return TopLevel | |
| 106 | + * @throws Exception | |
| 107 | + */ | |
| 108 | + public static function from(stdClass $obj): TopLevel { | |
| 109 | + return new TopLevel( | |
| 110 | + TopLevel::fromWaypoints($obj->{'waypoints'}) | |
| 111 | + ); | |
| 112 | + } | |
| 113 | + | |
| 114 | + /** | |
| 115 | + * @return TopLevel | |
| 116 | + */ | |
| 117 | + public static function sample(): TopLevel { | |
| 118 | + return new TopLevel( | |
| 119 | + TopLevel::sampleWaypoints() | |
| 120 | + ); | |
| 121 | + } | |
| 122 | +} | |
| 123 | + | |
| 124 | +// This is an autogenerated file:SCUBAWaypoint | |
| 125 | + | |
| 126 | +class SCUBAWaypoint { | |
| 127 | + private ?float $depth; // json:depth Optional | |
| 128 | + private ?IDCardHTTP $idCard; // json:idCard Optional | |
| 129 | + private ?Point $location; // json:location Optional | |
| 130 | + private ?SCUBAManeuver $maneuver; // json:maneuver Optional | |
| 131 | + | |
| 132 | + /** | |
| 133 | + * @param float|null $depth | |
| 134 | + * @param IDCardHTTP|null $idCard | |
| 135 | + * @param Point|null $location | |
| 136 | + * @param SCUBAManeuver|null $maneuver | |
| 137 | + */ | |
| 138 | + public function __construct(?float $depth, ?IDCardHTTP $idCard, ?Point $location, ?SCUBAManeuver $maneuver) { | |
| 139 | + $this->depth = $depth; | |
| 140 | + $this->idCard = $idCard; | |
| 141 | + $this->location = $location; | |
| 142 | + $this->maneuver = $maneuver; | |
| 143 | + } | |
| 144 | + | |
| 145 | + /** | |
| 146 | + * @param ?float $value | |
| 147 | + * @throws Exception | |
| 148 | + * @return ?float | |
| 149 | + */ | |
| 150 | + public static function fromDepth(?float $value): ?float { | |
| 151 | + if (!is_null($value)) { | |
| 152 | + return $value; /*float*/ | |
| 153 | + } else { | |
| 154 | + return null; | |
| 155 | + } | |
| 156 | + } | |
| 157 | + | |
| 158 | + /** | |
| 159 | + * @throws Exception | |
| 160 | + * @return ?float | |
| 161 | + */ | |
| 162 | + public function toDepth(): ?float { | |
| 163 | + if (SCUBAWaypoint::validateDepth($this->depth)) { | |
| 164 | + if (!is_null($this->depth)) { | |
| 165 | + return $this->depth; /*float*/ | |
| 166 | + } else { | |
| 167 | + return null; | |
| 168 | + } | |
| 169 | + } | |
| 170 | + throw new Exception('never get to this SCUBAWaypoint::depth'); | |
| 171 | + } | |
| 172 | + | |
| 173 | + /** | |
| 174 | + * @param float|null | |
| 175 | + * @return bool | |
| 176 | + * @throws Exception | |
| 177 | + */ | |
| 178 | + public static function validateDepth(?float $value): bool { | |
| 179 | + if (!is_null($value)) { | |
| 180 | + } | |
| 181 | + return true; | |
| 182 | + } | |
| 183 | + | |
| 184 | + /** | |
| 185 | + * @throws Exception | |
| 186 | + * @return ?float | |
| 187 | + */ | |
| 188 | + public function getDepth(): ?float { | |
| 189 | + if (SCUBAWaypoint::validateDepth($this->depth)) { | |
| 190 | + return $this->depth; | |
| 191 | + } | |
| 192 | + throw new Exception('never get to getDepth SCUBAWaypoint::depth'); | |
| 193 | + } | |
| 194 | + | |
| 195 | + /** | |
| 196 | + * @return ?float | |
| 197 | + */ | |
| 198 | + public static function sampleDepth(): ?float { | |
| 199 | + return 31.031; /*31:depth*/ | |
| 200 | + } | |
| 201 | + | |
| 202 | + /** | |
| 203 | + * @param ?stdClass $value | |
| 204 | + * @throws Exception | |
| 205 | + * @return ?IDCardHTTP | |
| 206 | + */ | |
| 207 | + public static function fromIDCard(?stdClass $value): ?IDCardHTTP { | |
| 208 | + if (!is_null($value)) { | |
| 209 | + return IDCardHTTP::from($value); /*class*/ | |
| 210 | + } else { | |
| 211 | + return null; | |
| 212 | + } | |
| 213 | + } | |
| 214 | + | |
| 215 | + /** | |
| 216 | + * @throws Exception | |
| 217 | + * @return ?stdClass | |
| 218 | + */ | |
| 219 | + public function toIDCard(): ?stdClass { | |
| 220 | + if (SCUBAWaypoint::validateIDCard($this->idCard)) { | |
| 221 | + if (!is_null($this->idCard)) { | |
| 222 | + return $this->idCard->to(); /*class*/ | |
| 223 | + } else { | |
| 224 | + return null; | |
| 225 | + } | |
| 226 | + } | |
| 227 | + throw new Exception('never get to this SCUBAWaypoint::idCard'); | |
| 228 | + } | |
| 229 | + | |
| 230 | + /** | |
| 231 | + * @param IDCardHTTP|null | |
| 232 | + * @return bool | |
| 233 | + * @throws Exception | |
| 234 | + */ | |
| 235 | + public static function validateIDCard(?IDCardHTTP $value): bool { | |
| 236 | + if (!is_null($value)) { | |
| 237 | + $value->validate(); | |
| 238 | + } | |
| 239 | + return true; | |
| 240 | + } | |
| 241 | + | |
| 242 | + /** | |
| 243 | + * @throws Exception | |
| 244 | + * @return ?IDCardHTTP | |
| 245 | + */ | |
| 246 | + public function getIDCard(): ?IDCardHTTP { | |
| 247 | + if (SCUBAWaypoint::validateIDCard($this->idCard)) { | |
| 248 | + return $this->idCard; | |
| 249 | + } | |
| 250 | + throw new Exception('never get to getIDCard SCUBAWaypoint::idCard'); | |
| 251 | + } | |
| 252 | + | |
| 253 | + /** | |
| 254 | + * @return ?IDCardHTTP | |
| 255 | + */ | |
| 256 | + public static function sampleIDCard(): ?IDCardHTTP { | |
| 257 | + return IDCardHTTP::sample(); /*32:idCard*/ | |
| 258 | + } | |
| 259 | + | |
| 260 | + /** | |
| 261 | + * @param ?stdClass $value | |
| 262 | + * @throws Exception | |
| 263 | + * @return ?Point | |
| 264 | + */ | |
| 265 | + public static function fromLocation(?stdClass $value): ?Point { | |
| 266 | + if (!is_null($value)) { | |
| 267 | + return Point::from($value); /*class*/ | |
| 268 | + } else { | |
| 269 | + return null; | |
| 270 | + } | |
| 271 | + } | |
| 272 | + | |
| 273 | + /** | |
| 274 | + * @throws Exception | |
| 275 | + * @return ?stdClass | |
| 276 | + */ | |
| 277 | + public function toLocation(): ?stdClass { | |
| 278 | + if (SCUBAWaypoint::validateLocation($this->location)) { | |
| 279 | + if (!is_null($this->location)) { | |
| 280 | + return $this->location->to(); /*class*/ | |
| 281 | + } else { | |
| 282 | + return null; | |
| 283 | + } | |
| 284 | + } | |
| 285 | + throw new Exception('never get to this SCUBAWaypoint::location'); | |
| 286 | + } | |
| 287 | + | |
| 288 | + /** | |
| 289 | + * @param Point|null | |
| 290 | + * @return bool | |
| 291 | + * @throws Exception | |
| 292 | + */ | |
| 293 | + public static function validateLocation(?Point $value): bool { | |
| 294 | + if (!is_null($value)) { | |
| 295 | + $value->validate(); | |
| 296 | + } | |
| 297 | + return true; | |
| 298 | + } | |
| 299 | + | |
| 300 | + /** | |
| 301 | + * @throws Exception | |
| 302 | + * @return ?Point | |
| 303 | + */ | |
| 304 | + public function getLocation(): ?Point { | |
| 305 | + if (SCUBAWaypoint::validateLocation($this->location)) { | |
| 306 | + return $this->location; | |
| 307 | + } | |
| 308 | + throw new Exception('never get to getLocation SCUBAWaypoint::location'); | |
| 309 | + } | |
| 310 | + | |
| 311 | + /** | |
| 312 | + * @return ?Point | |
| 313 | + */ | |
| 314 | + public static function sampleLocation(): ?Point { | |
| 315 | + return Point::sample(); /*33:location*/ | |
| 316 | + } | |
| 317 | + | |
| 318 | + /** | |
| 319 | + * @param ?string $value | |
| 320 | + * @throws Exception | |
| 321 | + * @return ?SCUBAManeuver | |
| 322 | + */ | |
| 323 | + public static function fromManeuver(?string $value): ?SCUBAManeuver { | |
| 324 | + if (!is_null($value)) { | |
| 325 | + return SCUBAManeuver::from($value); /*enum*/ | |
| 326 | + } else { | |
| 327 | + return null; | |
| 328 | + } | |
| 329 | + } | |
| 330 | + | |
| 331 | + /** | |
| 332 | + * @throws Exception | |
| 333 | + * @return ?string | |
| 334 | + */ | |
| 335 | + public function toManeuver(): ?string { | |
| 336 | + if (SCUBAWaypoint::validateManeuver($this->maneuver)) { | |
| 337 | + if (!is_null($this->maneuver)) { | |
| 338 | + return SCUBAManeuver::to($this->maneuver); /*enum*/ | |
| 339 | + } else { | |
| 340 | + return null; | |
| 341 | + } | |
| 342 | + } | |
| 343 | + throw new Exception('never get to this SCUBAWaypoint::maneuver'); | |
| 344 | + } | |
| 345 | + | |
| 346 | + /** | |
| 347 | + * @param SCUBAManeuver|null | |
| 348 | + * @return bool | |
| 349 | + * @throws Exception | |
| 350 | + */ | |
| 351 | + public static function validateManeuver(?SCUBAManeuver $value): bool { | |
| 352 | + if (!is_null($value)) { | |
| 353 | + SCUBAManeuver::to($value); | |
| 354 | + } | |
| 355 | + return true; | |
| 356 | + } | |
| 357 | + | |
| 358 | + /** | |
| 359 | + * @throws Exception | |
| 360 | + * @return ?SCUBAManeuver | |
| 361 | + */ | |
| 362 | + public function getManeuver(): ?SCUBAManeuver { | |
| 363 | + if (SCUBAWaypoint::validateManeuver($this->maneuver)) { | |
| 364 | + return $this->maneuver; | |
| 365 | + } | |
| 366 | + throw new Exception('never get to getManeuver SCUBAWaypoint::maneuver'); | |
| 367 | + } | |
| 368 | + | |
| 369 | + /** | |
| 370 | + * @return ?SCUBAManeuver | |
| 371 | + */ | |
| 372 | + public static function sampleManeuver(): ?SCUBAManeuver { | |
| 373 | + return SCUBAManeuver::sample(); /*enum*/ | |
| 374 | + } | |
| 375 | + | |
| 376 | + /** | |
| 377 | + * @throws Exception | |
| 378 | + * @return bool | |
| 379 | + */ | |
| 380 | + public function validate(): bool { | |
| 381 | + return SCUBAWaypoint::validateDepth($this->depth) | |
| 382 | + || SCUBAWaypoint::validateIDCard($this->idCard) | |
| 383 | + || SCUBAWaypoint::validateLocation($this->location) | |
| 384 | + || SCUBAWaypoint::validateManeuver($this->maneuver); | |
| 385 | + } | |
| 386 | + | |
| 387 | + /** | |
| 388 | + * @return stdClass | |
| 389 | + * @throws Exception | |
| 390 | + */ | |
| 391 | + public function to(): stdClass { | |
| 392 | + $out = new stdClass(); | |
| 393 | + $out->{'depth'} = $this->toDepth(); | |
| 394 | + $out->{'idCard'} = $this->toIDCard(); | |
| 395 | + $out->{'location'} = $this->toLocation(); | |
| 396 | + $out->{'maneuver'} = $this->toManeuver(); | |
| 397 | + return $out; | |
| 398 | + } | |
| 399 | + | |
| 400 | + /** | |
| 401 | + * @param stdClass $obj | |
| 402 | + * @return SCUBAWaypoint | |
| 403 | + * @throws Exception | |
| 404 | + */ | |
| 405 | + public static function from(stdClass $obj): SCUBAWaypoint { | |
| 406 | + return new SCUBAWaypoint( | |
| 407 | + SCUBAWaypoint::fromDepth($obj->{'depth'}) | |
| 408 | + ,SCUBAWaypoint::fromIDCard($obj->{'idCard'}) | |
| 409 | + ,SCUBAWaypoint::fromLocation($obj->{'location'}) | |
| 410 | + ,SCUBAWaypoint::fromManeuver($obj->{'maneuver'}) | |
| 411 | + ); | |
| 412 | + } | |
| 413 | + | |
| 414 | + /** | |
| 415 | + * @return SCUBAWaypoint | |
| 416 | + */ | |
| 417 | + public static function sample(): SCUBAWaypoint { | |
| 418 | + return new SCUBAWaypoint( | |
| 419 | + SCUBAWaypoint::sampleDepth() | |
| 420 | + ,SCUBAWaypoint::sampleIDCard() | |
| 421 | + ,SCUBAWaypoint::sampleLocation() | |
| 422 | + ,SCUBAWaypoint::sampleManeuver() | |
| 423 | + ); | |
| 424 | + } | |
| 425 | +} | |
| 426 | + | |
| 427 | +// This is an autogenerated file:IDCardHTTP | |
| 428 | + | |
| 429 | +class IDCardHTTP { | |
| 430 | + private ?string $value; // json:value Optional | |
| 431 | + | |
| 432 | + /** | |
| 433 | + * @param string|null $value | |
| 434 | + */ | |
| 435 | + public function __construct(?string $value) { | |
| 436 | + $this->value = $value; | |
| 437 | + } | |
| 438 | + | |
| 439 | + /** | |
| 440 | + * @param ?string $value | |
| 441 | + * @throws Exception | |
| 442 | + * @return ?string | |
| 443 | + */ | |
| 444 | + public static function fromValue(?string $value): ?string { | |
| 445 | + if (!is_null($value)) { | |
| 446 | + return $value; /*string*/ | |
| 447 | + } else { | |
| 448 | + return null; | |
| 449 | + } | |
| 450 | + } | |
| 451 | + | |
| 452 | + /** | |
| 453 | + * @throws Exception | |
| 454 | + * @return ?string | |
| 455 | + */ | |
| 456 | + public function toValue(): ?string { | |
| 457 | + if (IDCardHTTP::validateValue($this->value)) { | |
| 458 | + if (!is_null($this->value)) { | |
| 459 | + return $this->value; /*string*/ | |
| 460 | + } else { | |
| 461 | + return null; | |
| 462 | + } | |
| 463 | + } | |
| 464 | + throw new Exception('never get to this IDCardHTTP::value'); | |
| 465 | + } | |
| 466 | + | |
| 467 | + /** | |
| 468 | + * @param string|null | |
| 469 | + * @return bool | |
| 470 | + * @throws Exception | |
| 471 | + */ | |
| 472 | + public static function validateValue(?string $value): bool { | |
| 473 | + if (!is_null($value)) { | |
| 474 | + } | |
| 475 | + return true; | |
| 476 | + } | |
| 477 | + | |
| 478 | + /** | |
| 479 | + * @throws Exception | |
| 480 | + * @return ?string | |
| 481 | + */ | |
| 482 | + public function getValue(): ?string { | |
| 483 | + if (IDCardHTTP::validateValue($this->value)) { | |
| 484 | + return $this->value; | |
| 485 | + } | |
| 486 | + throw new Exception('never get to getValue IDCardHTTP::value'); | |
| 487 | + } | |
| 488 | + | |
| 489 | + /** | |
| 490 | + * @return ?string | |
| 491 | + */ | |
| 492 | + public static function sampleValue(): ?string { | |
| 493 | + return 'IDCardHTTP::value::31'; /*31:value*/ | |
| 494 | + } | |
| 495 | + | |
| 496 | + /** | |
| 497 | + * @throws Exception | |
| 498 | + * @return bool | |
| 499 | + */ | |
| 500 | + public function validate(): bool { | |
| 501 | + return IDCardHTTP::validateValue($this->value); | |
| 502 | + } | |
| 503 | + | |
| 504 | + /** | |
| 505 | + * @return stdClass | |
| 506 | + * @throws Exception | |
| 507 | + */ | |
| 508 | + public function to(): stdClass { | |
| 509 | + $out = new stdClass(); | |
| 510 | + $out->{'value'} = $this->toValue(); | |
| 511 | + return $out; | |
| 512 | + } | |
| 513 | + | |
| 514 | + /** | |
| 515 | + * @param stdClass $obj | |
| 516 | + * @return IDCardHTTP | |
| 517 | + * @throws Exception | |
| 518 | + */ | |
| 519 | + public static function from(stdClass $obj): IDCardHTTP { | |
| 520 | + return new IDCardHTTP( | |
| 521 | + IDCardHTTP::fromValue($obj->{'value'}) | |
| 522 | + ); | |
| 523 | + } | |
| 524 | + | |
| 525 | + /** | |
| 526 | + * @return IDCardHTTP | |
| 527 | + */ | |
| 528 | + public static function sample(): IDCardHTTP { | |
| 529 | + return new IDCardHTTP( | |
| 530 | + IDCardHTTP::sampleValue() | |
| 531 | + ); | |
| 532 | + } | |
| 533 | +} | |
| 534 | + | |
| 535 | +// This is an autogenerated file:Point | |
| 536 | + | |
| 537 | +class Point { | |
| 538 | + private ?float $latitude; // json:latitude Optional | |
| 539 | + private ?float $longitude; // json:longitude Optional | |
| 540 | + | |
| 541 | + /** | |
| 542 | + * @param float|null $latitude | |
| 543 | + * @param float|null $longitude | |
| 544 | + */ | |
| 545 | + public function __construct(?float $latitude, ?float $longitude) { | |
| 546 | + $this->latitude = $latitude; | |
| 547 | + $this->longitude = $longitude; | |
| 548 | + } | |
| 549 | + | |
| 550 | + /** | |
| 551 | + * @param ?float $value | |
| 552 | + * @throws Exception | |
| 553 | + * @return ?float | |
| 554 | + */ | |
| 555 | + public static function fromLatitude(?float $value): ?float { | |
| 556 | + if (!is_null($value)) { | |
| 557 | + return $value; /*float*/ | |
| 558 | + } else { | |
| 559 | + return null; | |
| 560 | + } | |
| 561 | + } | |
| 562 | + | |
| 563 | + /** | |
| 564 | + * @throws Exception | |
| 565 | + * @return ?float | |
| 566 | + */ | |
| 567 | + public function toLatitude(): ?float { | |
| 568 | + if (Point::validateLatitude($this->latitude)) { | |
| 569 | + if (!is_null($this->latitude)) { | |
| 570 | + return $this->latitude; /*float*/ | |
| 571 | + } else { | |
| 572 | + return null; | |
| 573 | + } | |
| 574 | + } | |
| 575 | + throw new Exception('never get to this Point::latitude'); | |
| 576 | + } | |
| 577 | + | |
| 578 | + /** | |
| 579 | + * @param float|null | |
| 580 | + * @return bool | |
| 581 | + * @throws Exception | |
| 582 | + */ | |
| 583 | + public static function validateLatitude(?float $value): bool { | |
| 584 | + if (!is_null($value)) { | |
| 585 | + } | |
| 586 | + return true; | |
| 587 | + } | |
| 588 | + | |
| 589 | + /** | |
| 590 | + * @throws Exception | |
| 591 | + * @return ?float | |
| 592 | + */ | |
| 593 | + public function getLatitude(): ?float { | |
| 594 | + if (Point::validateLatitude($this->latitude)) { | |
| 595 | + return $this->latitude; | |
| 596 | + } | |
| 597 | + throw new Exception('never get to getLatitude Point::latitude'); | |
| 598 | + } | |
| 599 | + | |
| 600 | + /** | |
| 601 | + * @return ?float | |
| 602 | + */ | |
| 603 | + public static function sampleLatitude(): ?float { | |
| 604 | + return 31.031; /*31:latitude*/ | |
| 605 | + } | |
| 606 | + | |
| 607 | + /** | |
| 608 | + * @param ?float $value | |
| 609 | + * @throws Exception | |
| 610 | + * @return ?float | |
| 611 | + */ | |
| 612 | + public static function fromLongitude(?float $value): ?float { | |
| 613 | + if (!is_null($value)) { | |
| 614 | + return $value; /*float*/ | |
| 615 | + } else { | |
| 616 | + return null; | |
| 617 | + } | |
| 618 | + } | |
| 619 | + | |
| 620 | + /** | |
| 621 | + * @throws Exception | |
| 622 | + * @return ?float | |
| 623 | + */ | |
| 624 | + public function toLongitude(): ?float { | |
| 625 | + if (Point::validateLongitude($this->longitude)) { | |
| 626 | + if (!is_null($this->longitude)) { | |
| 627 | + return $this->longitude; /*float*/ | |
| 628 | + } else { | |
| 629 | + return null; | |
| 630 | + } | |
| 631 | + } | |
| 632 | + throw new Exception('never get to this Point::longitude'); | |
| 633 | + } | |
| 634 | + | |
| 635 | + /** | |
| 636 | + * @param float|null | |
| 637 | + * @return bool | |
| 638 | + * @throws Exception | |
| 639 | + */ | |
| 640 | + public static function validateLongitude(?float $value): bool { | |
| 641 | + if (!is_null($value)) { | |
| 642 | + } | |
| 643 | + return true; | |
| 644 | + } | |
| 645 | + | |
| 646 | + /** | |
| 647 | + * @throws Exception | |
| 648 | + * @return ?float | |
| 649 | + */ | |
| 650 | + public function getLongitude(): ?float { | |
| 651 | + if (Point::validateLongitude($this->longitude)) { | |
| 652 | + return $this->longitude; | |
| 653 | + } | |
| 654 | + throw new Exception('never get to getLongitude Point::longitude'); | |
| 655 | + } | |
| 656 | + | |
| 657 | + /** | |
| 658 | + * @return ?float | |
| 659 | + */ | |
| 660 | + public static function sampleLongitude(): ?float { | |
| 661 | + return 32.032; /*32:longitude*/ | |
| 662 | + } | |
| 663 | + | |
| 664 | + /** | |
| 665 | + * @throws Exception | |
| 666 | + * @return bool | |
| 667 | + */ | |
| 668 | + public function validate(): bool { | |
| 669 | + return Point::validateLatitude($this->latitude) | |
| 670 | + || Point::validateLongitude($this->longitude); | |
| 671 | + } | |
| 672 | + | |
| 673 | + /** | |
| 674 | + * @return stdClass | |
| 675 | + * @throws Exception | |
| 676 | + */ | |
| 677 | + public function to(): stdClass { | |
| 678 | + $out = new stdClass(); | |
| 679 | + $out->{'latitude'} = $this->toLatitude(); | |
| 680 | + $out->{'longitude'} = $this->toLongitude(); | |
| 681 | + return $out; | |
| 682 | + } | |
| 683 | + | |
| 684 | + /** | |
| 685 | + * @param stdClass $obj | |
| 686 | + * @return Point | |
| 687 | + * @throws Exception | |
| 688 | + */ | |
| 689 | + public static function from(stdClass $obj): Point { | |
| 690 | + return new Point( | |
| 691 | + Point::fromLatitude($obj->{'latitude'}) | |
| 692 | + ,Point::fromLongitude($obj->{'longitude'}) | |
| 693 | + ); | |
| 694 | + } | |
| 695 | + | |
| 696 | + /** | |
| 697 | + * @return Point | |
| 698 | + */ | |
| 699 | + public static function sample(): Point { | |
| 700 | + return new Point( | |
| 701 | + Point::sampleLatitude() | |
| 702 | + ,Point::sampleLongitude() | |
| 703 | + ); | |
| 704 | + } | |
| 705 | +} | |
| 706 | + | |
| 707 | +// This is an autogenerated file:SCUBAManeuver | |
| 708 | + | |
| 709 | +class SCUBAManeuver { | |
| 710 | + public static SCUBAManeuver $ASCENT; | |
| 711 | + public static SCUBAManeuver $DESCENT; | |
| 712 | + public static SCUBAManeuver $LEVEL; | |
| 713 | + public static function init() { | |
| 714 | + SCUBAManeuver::$ASCENT = new SCUBAManeuver('ASCENT'); | |
| 715 | + SCUBAManeuver::$DESCENT = new SCUBAManeuver('DESCENT'); | |
| 716 | + SCUBAManeuver::$LEVEL = new SCUBAManeuver('LEVEL'); | |
| 717 | + } | |
| 718 | + private string $enum; | |
| 719 | + public function __construct(string $enum) { | |
| 720 | + $this->enum = $enum; | |
| 721 | + } | |
| 722 | + | |
| 723 | + /** | |
| 724 | + * @param SCUBAManeuver | |
| 725 | + * @return string | |
| 726 | + * @throws Exception | |
| 727 | + */ | |
| 728 | + public static function to(SCUBAManeuver $obj): string { | |
| 729 | + switch ($obj->enum) { | |
| 730 | + case SCUBAManeuver::$ASCENT->enum: return 'ASCENT'; | |
| 731 | + case SCUBAManeuver::$DESCENT->enum: return 'DESCENT'; | |
| 732 | + case SCUBAManeuver::$LEVEL->enum: return 'LEVEL'; | |
| 733 | + } | |
| 734 | + throw new Exception('the give value is not an enum-value.'); | |
| 735 | + } | |
| 736 | + | |
| 737 | + /** | |
| 738 | + * @param mixed | |
| 739 | + * @return SCUBAManeuver | |
| 740 | + * @throws Exception | |
| 741 | + */ | |
| 742 | + public static function from($obj): SCUBAManeuver { | |
| 743 | + switch ($obj) { | |
| 744 | + case 'ASCENT': return SCUBAManeuver::$ASCENT; | |
| 745 | + case 'DESCENT': return SCUBAManeuver::$DESCENT; | |
| 746 | + case 'LEVEL': return SCUBAManeuver::$LEVEL; | |
| 747 | + } | |
| 748 | + throw new Exception("Cannot deserialize SCUBAManeuver"); | |
| 749 | + } | |
| 750 | + | |
| 751 | + /** | |
| 752 | + * @return SCUBAManeuver | |
| 753 | + */ | |
| 754 | + public static function sample(): SCUBAManeuver { | |
| 755 | + return SCUBAManeuver::$ASCENT; | |
| 756 | + } | |
| 757 | +} | |
| 758 | +SCUBAManeuver::init(); |
Aschema-pikedefault / TopLevel.pmod+112 −0
| @@ -0,0 +1,112 @@ | ||
| 1 | +// This source has been automatically generated by quicktype. | |
| 2 | +// ( https://github.com/quicktype/quicktype ) | |
| 3 | +// | |
| 4 | +// To use this code, simply import it into your project as a Pike module. | |
| 5 | +// To JSON-encode your object, you can pass it to `Standards.JSON.encode` | |
| 6 | +// or call `encode_json` on it. | |
| 7 | +// | |
| 8 | +// To decode a JSON string, first pass it to `Standards.JSON.decode`, | |
| 9 | +// and then pass the result to `<YourClass>_from_JSON`. | |
| 10 | +// It will return an instance of <YourClass>. | |
| 11 | +// Bear in mind that these functions have unexpected behavior, | |
| 12 | +// and will likely throw an error, if the JSON string does not | |
| 13 | +// match the expected interface, even if the JSON itself is valid. | |
| 14 | + | |
| 15 | +// A SCUBA dive log with waypoints | |
| 16 | +class TopLevel { | |
| 17 | + array(ScubaWaypoint)|mixed waypoints; // json: "waypoints" | |
| 18 | + | |
| 19 | + string encode_json() { | |
| 20 | + mapping(string:mixed) json = ([ | |
| 21 | + "waypoints" : waypoints, | |
| 22 | + ]); | |
| 23 | + | |
| 24 | + return Standards.JSON.encode(json); | |
| 25 | + } | |
| 26 | +} | |
| 27 | + | |
| 28 | +TopLevel TopLevel_from_JSON(mixed json) { | |
| 29 | + TopLevel retval = TopLevel(); | |
| 30 | + | |
| 31 | + retval.waypoints = json["waypoints"]; | |
| 32 | + | |
| 33 | + return retval; | |
| 34 | +} | |
| 35 | + | |
| 36 | +class ScubaWaypoint { | |
| 37 | + float|mixed depth; // json: "depth" | |
| 38 | + IdCardHttp|mixed id_card; // json: "idCard" | |
| 39 | + Point|mixed location; // json: "location" | |
| 40 | + ScubaManeuver|mixed maneuver; // json: "maneuver" | |
| 41 | + | |
| 42 | + string encode_json() { | |
| 43 | + mapping(string:mixed) json = ([ | |
| 44 | + "depth" : depth, | |
| 45 | + "idCard" : id_card, | |
| 46 | + "location" : location, | |
| 47 | + "maneuver" : maneuver, | |
| 48 | + ]); | |
| 49 | + | |
| 50 | + return Standards.JSON.encode(json); | |
| 51 | + } | |
| 52 | +} | |
| 53 | + | |
| 54 | +ScubaWaypoint ScubaWaypoint_from_JSON(mixed json) { | |
| 55 | + ScubaWaypoint retval = ScubaWaypoint(); | |
| 56 | + | |
| 57 | + retval.depth = json["depth"]; | |
| 58 | + retval.id_card = json["idCard"]; | |
| 59 | + retval.location = json["location"]; | |
| 60 | + retval.maneuver = json["maneuver"]; | |
| 61 | + | |
| 62 | + return retval; | |
| 63 | +} | |
| 64 | + | |
| 65 | +class IdCardHttp { | |
| 66 | + mixed|string value; // json: "value" | |
| 67 | + | |
| 68 | + string encode_json() { | |
| 69 | + mapping(string:mixed) json = ([ | |
| 70 | + "value" : value, | |
| 71 | + ]); | |
| 72 | + | |
| 73 | + return Standards.JSON.encode(json); | |
| 74 | + } | |
| 75 | +} | |
| 76 | + | |
| 77 | +IdCardHttp IdCardHttp_from_JSON(mixed json) { | |
| 78 | + IdCardHttp retval = IdCardHttp(); | |
| 79 | + | |
| 80 | + retval.value = json["value"]; | |
| 81 | + | |
| 82 | + return retval; | |
| 83 | +} | |
| 84 | + | |
| 85 | +class Point { | |
| 86 | + float|mixed latitude; // json: "latitude" | |
| 87 | + float|mixed longitude; // json: "longitude" | |
| 88 | + | |
| 89 | + string encode_json() { | |
| 90 | + mapping(string:mixed) json = ([ | |
| 91 | + "latitude" : latitude, | |
| 92 | + "longitude" : longitude, | |
| 93 | + ]); | |
| 94 | + | |
| 95 | + return Standards.JSON.encode(json); | |
| 96 | + } | |
| 97 | +} | |
| 98 | + | |
| 99 | +Point Point_from_JSON(mixed json) { | |
| 100 | + Point retval = Point(); | |
| 101 | + | |
| 102 | + retval.latitude = json["latitude"]; | |
| 103 | + retval.longitude = json["longitude"]; | |
| 104 | + | |
| 105 | + return retval; | |
| 106 | +} | |
| 107 | + | |
| 108 | +enum ScubaManeuver { | |
| 109 | + ASCENT = "ASCENT", // json: "ASCENT" | |
| 110 | + DESCENT = "DESCENT", // json: "DESCENT" | |
| 111 | + LEVEL = "LEVEL", // json: "LEVEL" | |
| 112 | +} |
Aschema-pythondefault / quicktype.py+151 −0
| @@ -0,0 +1,151 @@ | ||
| 1 | +from dataclasses import dataclass | |
| 2 | +from typing import Any, TypeVar, Type, cast, Callable | |
| 3 | +from enum import Enum | |
| 4 | + | |
| 5 | + | |
| 6 | +T = TypeVar("T") | |
| 7 | +EnumT = TypeVar("EnumT", bound=Enum) | |
| 8 | + | |
| 9 | + | |
| 10 | +def from_str(x: Any) -> str: | |
| 11 | + assert isinstance(x, str) | |
| 12 | + return x | |
| 13 | + | |
| 14 | + | |
| 15 | +def from_none(x: Any) -> Any: | |
| 16 | + assert x is None | |
| 17 | + return x | |
| 18 | + | |
| 19 | + | |
| 20 | +def from_union(fs, x): | |
| 21 | + for f in fs: | |
| 22 | + try: | |
| 23 | + return f(x) | |
| 24 | + except: | |
| 25 | + pass | |
| 26 | + assert False | |
| 27 | + | |
| 28 | + | |
| 29 | +def from_float(x: Any) -> float: | |
| 30 | + assert isinstance(x, (float, int)) and not isinstance(x, bool) | |
| 31 | + return float(x) | |
| 32 | + | |
| 33 | + | |
| 34 | +def to_float(x: Any) -> float: | |
| 35 | + assert isinstance(x, (int, float)) | |
| 36 | + return x | |
| 37 | + | |
| 38 | + | |
| 39 | +def to_class(c: Type[T], x: Any) -> dict: | |
| 40 | + assert isinstance(x, c) | |
| 41 | + return cast(Any, x).to_dict() | |
| 42 | + | |
| 43 | + | |
| 44 | +def to_enum(c: Type[EnumT], x: Any) -> EnumT: | |
| 45 | + assert isinstance(x, c) | |
| 46 | + return x.value | |
| 47 | + | |
| 48 | + | |
| 49 | +def from_list(f: Callable[[Any], T], x: Any) -> list[T]: | |
| 50 | + assert isinstance(x, list) | |
| 51 | + return [f(y) for y in x] | |
| 52 | + | |
| 53 | + | |
| 54 | +@dataclass | |
| 55 | +class IDCardHTTP: | |
| 56 | + value: str | None = None | |
| 57 | + | |
| 58 | + @staticmethod | |
| 59 | + def from_dict(obj: Any) -> 'IDCardHTTP': | |
| 60 | + assert isinstance(obj, dict) | |
| 61 | + value = from_union([from_str, from_none], obj.get("value")) | |
| 62 | + return IDCardHTTP(value) | |
| 63 | + | |
| 64 | + def to_dict(self) -> dict: | |
| 65 | + result: dict = {} | |
| 66 | + if self.value is not None: | |
| 67 | + result["value"] = from_union([from_str, from_none], self.value) | |
| 68 | + return result | |
| 69 | + | |
| 70 | + | |
| 71 | +@dataclass | |
| 72 | +class Point: | |
| 73 | + latitude: float | None = None | |
| 74 | + longitude: float | None = None | |
| 75 | + | |
| 76 | + @staticmethod | |
| 77 | + def from_dict(obj: Any) -> 'Point': | |
| 78 | + assert isinstance(obj, dict) | |
| 79 | + latitude = from_union([from_float, from_none], obj.get("latitude")) | |
| 80 | + longitude = from_union([from_float, from_none], obj.get("longitude")) | |
| 81 | + return Point(latitude, longitude) | |
| 82 | + | |
| 83 | + def to_dict(self) -> dict: | |
| 84 | + result: dict = {} | |
| 85 | + if self.latitude is not None: | |
| 86 | + result["latitude"] = from_union([to_float, from_none], self.latitude) | |
| 87 | + if self.longitude is not None: | |
| 88 | + result["longitude"] = from_union([to_float, from_none], self.longitude) | |
| 89 | + return result | |
| 90 | + | |
| 91 | + | |
| 92 | +class SCUBAManeuver(Enum): | |
| 93 | + ASCENT = "ASCENT" | |
| 94 | + DESCENT = "DESCENT" | |
| 95 | + LEVEL = "LEVEL" | |
| 96 | + | |
| 97 | + | |
| 98 | +@dataclass | |
| 99 | +class SCUBAWaypoint: | |
| 100 | + depth: float | None = None | |
| 101 | + id_card: IDCardHTTP | None = None | |
| 102 | + location: Point | None = None | |
| 103 | + maneuver: SCUBAManeuver | None = None | |
| 104 | + | |
| 105 | + @staticmethod | |
| 106 | + def from_dict(obj: Any) -> 'SCUBAWaypoint': | |
| 107 | + assert isinstance(obj, dict) | |
| 108 | + depth = from_union([from_float, from_none], obj.get("depth")) | |
| 109 | + id_card = from_union([IDCardHTTP.from_dict, from_none], obj.get("idCard")) | |
| 110 | + location = from_union([Point.from_dict, from_none], obj.get("location")) | |
| 111 | + maneuver = from_union([SCUBAManeuver, from_none], obj.get("maneuver")) | |
| 112 | + return SCUBAWaypoint(depth, id_card, location, maneuver) | |
| 113 | + | |
| 114 | + def to_dict(self) -> dict: | |
| 115 | + result: dict = {} | |
| 116 | + if self.depth is not None: | |
| 117 | + result["depth"] = from_union([to_float, from_none], self.depth) | |
| 118 | + if self.id_card is not None: | |
| 119 | + result["idCard"] = from_union([lambda x: to_class(IDCardHTTP, x), from_none], self.id_card) | |
| 120 | + if self.location is not None: | |
| 121 | + result["location"] = from_union([lambda x: to_class(Point, x), from_none], self.location) | |
| 122 | + if self.maneuver is not None: | |
| 123 | + result["maneuver"] = from_union([lambda x: to_enum(SCUBAManeuver, x), from_none], self.maneuver) | |
| 124 | + return result | |
| 125 | + | |
| 126 | + | |
| 127 | +@dataclass | |
| 128 | +class TopLevel: | |
| 129 | + """A SCUBA dive log with waypoints""" | |
| 130 | + | |
| 131 | + waypoints: list[SCUBAWaypoint] | None = None | |
| 132 | + | |
| 133 | + @staticmethod | |
| 134 | + def from_dict(obj: Any) -> 'TopLevel': | |
| 135 | + assert isinstance(obj, dict) | |
| 136 | + waypoints = from_union([lambda x: from_list(SCUBAWaypoint.from_dict, x), from_none], obj.get("waypoints")) | |
| 137 | + return TopLevel(waypoints) | |
| 138 | + | |
| 139 | + def to_dict(self) -> dict: | |
| 140 | + result: dict = {} | |
| 141 | + if self.waypoints is not None: | |
| 142 | + result["waypoints"] = from_union([lambda x: from_list(lambda x: to_class(SCUBAWaypoint, x), x), from_none], self.waypoints) | |
| 143 | + return result | |
| 144 | + | |
| 145 | + | |
| 146 | +def top_level_from_dict(s: Any) -> TopLevel: | |
| 147 | + return TopLevel.from_dict(s) | |
| 148 | + | |
| 149 | + | |
| 150 | +def top_level_to_dict(x: TopLevel) -> Any: | |
| 151 | + return to_class(TopLevel, x) |
Aschema-rubydefault / TopLevel.rb+141 −0
| @@ -0,0 +1,141 @@ | ||
| 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.waypoints&.first.location&.latitude | |
| 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 | + SCUBAManeuver = Strict::String.enum("ASCENT", "DESCENT", "LEVEL") | |
| 22 | +end | |
| 23 | + | |
| 24 | +class IDCardHTTP < Dry::Struct | |
| 25 | + attribute :value, Types::String.optional | |
| 26 | + | |
| 27 | + def self.from_dynamic!(d) | |
| 28 | + d = Types::Hash[d] | |
| 29 | + new( | |
| 30 | + value: d["value"], | |
| 31 | + ) | |
| 32 | + end | |
| 33 | + | |
| 34 | + def self.from_json!(json) | |
| 35 | + from_dynamic!(JSON.parse(json)) | |
| 36 | + end | |
| 37 | + | |
| 38 | + def to_dynamic | |
| 39 | + { | |
| 40 | + "value" => value, | |
| 41 | + } | |
| 42 | + end | |
| 43 | + | |
| 44 | + def to_json(options = nil) | |
| 45 | + JSON.generate(to_dynamic, options) | |
| 46 | + end | |
| 47 | +end | |
| 48 | + | |
| 49 | +class Point < Dry::Struct | |
| 50 | + attribute :latitude, Types::Double.optional | |
| 51 | + attribute :longitude, Types::Double.optional | |
| 52 | + | |
| 53 | + def self.from_dynamic!(d) | |
| 54 | + d = Types::Hash[d] | |
| 55 | + new( | |
| 56 | + latitude: d["latitude"], | |
| 57 | + longitude: d["longitude"], | |
| 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 | + "latitude" => latitude, | |
| 68 | + "longitude" => longitude, | |
| 69 | + } | |
| 70 | + end | |
| 71 | + | |
| 72 | + def to_json(options = nil) | |
| 73 | + JSON.generate(to_dynamic, options) | |
| 74 | + end | |
| 75 | +end | |
| 76 | + | |
| 77 | +module SCUBAManeuver | |
| 78 | + Ascent = "ASCENT" | |
| 79 | + Descent = "DESCENT" | |
| 80 | + Level = "LEVEL" | |
| 81 | +end | |
| 82 | + | |
| 83 | +class SCUBAWaypoint < Dry::Struct | |
| 84 | + attribute :depth, Types::Double.optional | |
| 85 | + attribute :id_card, IDCardHTTP.optional | |
| 86 | + attribute :location, Point.optional | |
| 87 | + attribute :maneuver, Types::SCUBAManeuver.optional | |
| 88 | + | |
| 89 | + def self.from_dynamic!(d) | |
| 90 | + d = Types::Hash[d] | |
| 91 | + new( | |
| 92 | + depth: d["depth"], | |
| 93 | + id_card: d["idCard"] ? IDCardHTTP.from_dynamic!(d["idCard"]) : nil, | |
| 94 | + location: d["location"] ? Point.from_dynamic!(d["location"]) : nil, | |
| 95 | + maneuver: d["maneuver"], | |
| 96 | + ) | |
| 97 | + end | |
| 98 | + | |
| 99 | + def self.from_json!(json) | |
| 100 | + from_dynamic!(JSON.parse(json)) | |
| 101 | + end | |
| 102 | + | |
| 103 | + def to_dynamic | |
| 104 | + { | |
| 105 | + "depth" => depth, | |
| 106 | + "idCard" => id_card&.to_dynamic, | |
| 107 | + "location" => location&.to_dynamic, | |
| 108 | + "maneuver" => maneuver, | |
| 109 | + } | |
| 110 | + end | |
| 111 | + | |
| 112 | + def to_json(options = nil) | |
| 113 | + JSON.generate(to_dynamic, options) | |
| 114 | + end | |
| 115 | +end | |
| 116 | + | |
| 117 | +# A SCUBA dive log with waypoints | |
| 118 | +class TopLevel < Dry::Struct | |
| 119 | + attribute :waypoints, Types.Array(SCUBAWaypoint).optional | |
| 120 | + | |
| 121 | + def self.from_dynamic!(d) | |
| 122 | + d = Types::Hash[d] | |
| 123 | + new( | |
| 124 | + waypoints: d["waypoints"]&.map { |x| SCUBAWaypoint.from_dynamic!(x) }, | |
| 125 | + ) | |
| 126 | + end | |
| 127 | + | |
| 128 | + def self.from_json!(json) | |
| 129 | + from_dynamic!(JSON.parse(json)) | |
| 130 | + end | |
| 131 | + | |
| 132 | + def to_dynamic | |
| 133 | + { | |
| 134 | + "waypoints" => waypoints&.map { |x| x.to_dynamic }, | |
| 135 | + } | |
| 136 | + end | |
| 137 | + | |
| 138 | + def to_json(options = nil) | |
| 139 | + JSON.generate(to_dynamic, options) | |
| 140 | + end | |
| 141 | +end |
Aschema-rustdefault / module_under_test.rs+56 −0
| @@ -0,0 +1,56 @@ | ||
| 1 | +// Example code that deserializes and serializes the model. | |
| 2 | +// extern crate serde; | |
| 3 | +// #[macro_use] | |
| 4 | +// extern crate serde_derive; | |
| 5 | +// extern crate serde_json; | |
| 6 | +// | |
| 7 | +// use generated_module::TopLevel; | |
| 8 | +// | |
| 9 | +// fn main() { | |
| 10 | +// let json = r#"{"answer": 42}"#; | |
| 11 | +// let model: TopLevel = serde_json::from_str(&json).unwrap(); | |
| 12 | +// } | |
| 13 | + | |
| 14 | +use serde::{Serialize, Deserialize}; | |
| 15 | + | |
| 16 | +/// A SCUBA dive log with waypoints | |
| 17 | +#[derive(Debug, Clone, Serialize, Deserialize)] | |
| 18 | +pub struct TopLevel { | |
| 19 | + pub waypoints: Option<Vec<ScubaWaypoint>>, | |
| 20 | +} | |
| 21 | + | |
| 22 | +#[derive(Debug, Clone, Serialize, Deserialize)] | |
| 23 | +#[serde(rename_all = "camelCase")] | |
| 24 | +pub struct ScubaWaypoint { | |
| 25 | + pub depth: Option<f64>, | |
| 26 | + | |
| 27 | + pub id_card: Option<IdCardHttp>, | |
| 28 | + | |
| 29 | + pub location: Option<Point>, | |
| 30 | + | |
| 31 | + pub maneuver: Option<ScubaManeuver>, | |
| 32 | +} | |
| 33 | + | |
| 34 | +#[derive(Debug, Clone, Serialize, Deserialize)] | |
| 35 | +pub struct IdCardHttp { | |
| 36 | + pub value: Option<String>, | |
| 37 | +} | |
| 38 | + | |
| 39 | +#[derive(Debug, Clone, Serialize, Deserialize)] | |
| 40 | +pub struct Point { | |
| 41 | + pub latitude: Option<f64>, | |
| 42 | + | |
| 43 | + pub longitude: Option<f64>, | |
| 44 | +} | |
| 45 | + | |
| 46 | +#[derive(Debug, Clone, Serialize, Deserialize)] | |
| 47 | +pub enum ScubaManeuver { | |
| 48 | + #[serde(rename = "ASCENT")] | |
| 49 | + Ascent, | |
| 50 | + | |
| 51 | + #[serde(rename = "DESCENT")] | |
| 52 | + Descent, | |
| 53 | + | |
| 54 | + #[serde(rename = "LEVEL")] | |
| 55 | + Level, | |
| 56 | +} |
Aschema-scala3-upickledefault / TopLevel.scala+108 −0
| @@ -0,0 +1,108 @@ | ||
| 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 | +/** | |
| 69 | + * A SCUBA dive log with waypoints | |
| 70 | + */ | |
| 71 | +case class TopLevel ( | |
| 72 | + val waypoints : Option[Seq[SCUBAWaypoint]] = None | |
| 73 | +) derives OptionPickler.ReadWriter | |
| 74 | + | |
| 75 | +case class SCUBAWaypoint ( | |
| 76 | + val depth : Option[Double] = None, | |
| 77 | + val idCard : Option[IDCardHTTP] = None, | |
| 78 | + val location : Option[Point] = None, | |
| 79 | + val maneuver : Option[SCUBAManeuver] = None | |
| 80 | +) derives OptionPickler.ReadWriter | |
| 81 | + | |
| 82 | +case class IDCardHTTP ( | |
| 83 | + val value : Option[String] = None | |
| 84 | +) derives OptionPickler.ReadWriter | |
| 85 | + | |
| 86 | +case class Point ( | |
| 87 | + val latitude : Option[Double] = None, | |
| 88 | + val longitude : Option[Double] = None | |
| 89 | +) derives OptionPickler.ReadWriter | |
| 90 | + | |
| 91 | +enum SCUBAManeuver : | |
| 92 | + case Ascent | |
| 93 | + case Descent | |
| 94 | + case Level | |
| 95 | + | |
| 96 | +given OptionPickler.ReadWriter[SCUBAManeuver] = OptionPickler.readwriter[String].bimap[SCUBAManeuver]( | |
| 97 | + { | |
| 98 | + case SCUBAManeuver.Ascent => "ASCENT" | |
| 99 | + case SCUBAManeuver.Descent => "DESCENT" | |
| 100 | + case SCUBAManeuver.Level => "LEVEL" | |
| 101 | + }, | |
| 102 | + { | |
| 103 | + case "ASCENT" => SCUBAManeuver.Ascent | |
| 104 | + case "DESCENT" => SCUBAManeuver.Descent | |
| 105 | + case "LEVEL" => SCUBAManeuver.Level | |
| 106 | + case other => throw new upickle.core.Abort("invalid SCUBAManeuver: " + other) | |
| 107 | + } | |
| 108 | +) |
Aschema-scala3default / TopLevel.scala+48 −0
| @@ -0,0 +1,48 @@ | ||
| 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 | +/** | |
| 11 | + * A SCUBA dive log with waypoints | |
| 12 | + */ | |
| 13 | +case class TopLevel ( | |
| 14 | + val waypoints : Option[Seq[SCUBAWaypoint]] = None | |
| 15 | +) derives Encoder.AsObject, Decoder | |
| 16 | + | |
| 17 | +case class SCUBAWaypoint ( | |
| 18 | + val depth : Option[Double] = None, | |
| 19 | + val idCard : Option[IDCardHTTP] = None, | |
| 20 | + val location : Option[Point] = None, | |
| 21 | + val maneuver : Option[SCUBAManeuver] = None | |
| 22 | +) derives Encoder.AsObject, Decoder | |
| 23 | + | |
| 24 | +case class IDCardHTTP ( | |
| 25 | + val value : Option[String] = None | |
| 26 | +) derives Encoder.AsObject, Decoder | |
| 27 | + | |
| 28 | +case class Point ( | |
| 29 | + val latitude : Option[Double] = None, | |
| 30 | + val longitude : Option[Double] = None | |
| 31 | +) derives Encoder.AsObject, Decoder | |
| 32 | + | |
| 33 | +enum SCUBAManeuver : | |
| 34 | + case Ascent | |
| 35 | + case Descent | |
| 36 | + case Level | |
| 37 | + | |
| 38 | +given Decoder[SCUBAManeuver] = Decoder.decodeString.emap { | |
| 39 | + case "ASCENT" => scala.Right(SCUBAManeuver.Ascent) | |
| 40 | + case "DESCENT" => scala.Right(SCUBAManeuver.Descent) | |
| 41 | + case "LEVEL" => scala.Right(SCUBAManeuver.Level) | |
| 42 | + case other => scala.Left("invalid SCUBAManeuver: " + other) | |
| 43 | +} | |
| 44 | +given Encoder[SCUBAManeuver] = Encoder.encodeString.contramap { | |
| 45 | + case SCUBAManeuver.Ascent => "ASCENT" | |
| 46 | + case SCUBAManeuver.Descent => "DESCENT" | |
| 47 | + case SCUBAManeuver.Level => "LEVEL" | |
| 48 | +} |
Aschema-schemadefault / TopLevel.schema+75 −0
| @@ -0,0 +1,75 @@ | ||
| 1 | +{ | |
| 2 | + "$schema": "http://json-schema.org/draft-06/schema#", | |
| 3 | + "$ref": "#/definitions/TopLevel", | |
| 4 | + "definitions": { | |
| 5 | + "TopLevel": { | |
| 6 | + "type": "object", | |
| 7 | + "additionalProperties": {}, | |
| 8 | + "properties": { | |
| 9 | + "waypoints": { | |
| 10 | + "type": "array", | |
| 11 | + "items": { | |
| 12 | + "$ref": "#/definitions/SCUBAWaypoint" | |
| 13 | + } | |
| 14 | + } | |
| 15 | + }, | |
| 16 | + "required": [], | |
| 17 | + "title": "TopLevel", | |
| 18 | + "description": "A SCUBA dive log with waypoints" | |
| 19 | + }, | |
| 20 | + "SCUBAWaypoint": { | |
| 21 | + "type": "object", | |
| 22 | + "additionalProperties": {}, | |
| 23 | + "properties": { | |
| 24 | + "depth": { | |
| 25 | + "type": "number" | |
| 26 | + }, | |
| 27 | + "idCard": { | |
| 28 | + "$ref": "#/definitions/IDCardHTTP" | |
| 29 | + }, | |
| 30 | + "location": { | |
| 31 | + "$ref": "#/definitions/Point" | |
| 32 | + }, | |
| 33 | + "maneuver": { | |
| 34 | + "$ref": "#/definitions/SCUBAManeuver" | |
| 35 | + } | |
| 36 | + }, | |
| 37 | + "required": [], | |
| 38 | + "title": "SCUBAWaypoint" | |
| 39 | + }, | |
| 40 | + "IDCardHTTP": { | |
| 41 | + "type": "object", | |
| 42 | + "additionalProperties": {}, | |
| 43 | + "properties": { | |
| 44 | + "value": { | |
| 45 | + "type": "string" | |
| 46 | + } | |
| 47 | + }, | |
| 48 | + "required": [], | |
| 49 | + "title": "IDCardHTTP" | |
| 50 | + }, | |
| 51 | + "Point": { | |
| 52 | + "type": "object", | |
| 53 | + "additionalProperties": {}, | |
| 54 | + "properties": { | |
| 55 | + "latitude": { | |
| 56 | + "type": "number" | |
| 57 | + }, | |
| 58 | + "longitude": { | |
| 59 | + "type": "number" | |
| 60 | + } | |
| 61 | + }, | |
| 62 | + "required": [], | |
| 63 | + "title": "Point" | |
| 64 | + }, | |
| 65 | + "SCUBAManeuver": { | |
| 66 | + "type": "string", | |
| 67 | + "enum": [ | |
| 68 | + "ASCENT", | |
| 69 | + "DESCENT", | |
| 70 | + "LEVEL" | |
| 71 | + ], | |
| 72 | + "title": "SCUBAManeuver" | |
| 73 | + } | |
| 74 | + } | |
| 75 | +} |
Aschema-typescriptdefault / TopLevel.ts+226 −0
| @@ -0,0 +1,226 @@ | ||
| 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 | +/** | |
| 11 | + * A SCUBA dive log with waypoints | |
| 12 | + */ | |
| 13 | +export interface TopLevel { | |
| 14 | + waypoints?: SCUBAWaypoint[]; | |
| 15 | + [property: string]: unknown; | |
| 16 | +} | |
| 17 | + | |
| 18 | +export interface SCUBAWaypoint { | |
| 19 | + depth?: number; | |
| 20 | + idCard?: IDCardHTTP; | |
| 21 | + location?: Point; | |
| 22 | + maneuver?: SCUBAManeuver; | |
| 23 | + [property: string]: unknown; | |
| 24 | +} | |
| 25 | + | |
| 26 | +export interface IDCardHTTP { | |
| 27 | + value?: string; | |
| 28 | + [property: string]: unknown; | |
| 29 | +} | |
| 30 | + | |
| 31 | +export interface Point { | |
| 32 | + latitude?: number; | |
| 33 | + longitude?: number; | |
| 34 | + [property: string]: unknown; | |
| 35 | +} | |
| 36 | + | |
| 37 | +export type SCUBAManeuver = "ASCENT" | "DESCENT" | "LEVEL"; | |
| 38 | + | |
| 39 | +// Converts JSON strings to/from your types | |
| 40 | +// and asserts the results of JSON.parse at runtime | |
| 41 | +export class Convert { | |
| 42 | + public static toTopLevel(json: string): TopLevel { | |
| 43 | + return cast(JSON.parse(json), r("TopLevel")); | |
| 44 | + } | |
| 45 | + | |
| 46 | + public static topLevelToJson(value: TopLevel): string { | |
| 47 | + return JSON.stringify(uncast(value, r("TopLevel")), null, 2); | |
| 48 | + } | |
| 49 | +} | |
| 50 | + | |
| 51 | +function invalidValue(typ: any, val: any, key: any, parent: any = ''): never { | |
| 52 | + const prettyTyp = prettyTypeName(typ); | |
| 53 | + const parentText = parent ? ` on ${parent}` : ''; | |
| 54 | + const keyText = key ? ` for key "${key}"` : ''; | |
| 55 | + throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`); | |
| 56 | +} | |
| 57 | + | |
| 58 | +function prettyTypeName(typ: any): string { | |
| 59 | + if (Array.isArray(typ)) { | |
| 60 | + if (typ.length === 2 && typ[0] === undefined) { | |
| 61 | + return `an optional ${prettyTypeName(typ[1])}`; | |
| 62 | + } else { | |
| 63 | + return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`; | |
| 64 | + } | |
| 65 | + } else if (typeof typ === "object" && typ.literal !== undefined) { | |
| 66 | + return typ.literal; | |
| 67 | + } else { | |
| 68 | + return typeof typ; | |
| 69 | + } | |
| 70 | +} | |
| 71 | + | |
| 72 | +function jsonToJSProps(typ: any): any { | |
| 73 | + if (typ.jsonToJS === undefined) { | |
| 74 | + const map: any = {}; | |
| 75 | + typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ }); | |
| 76 | + typ.jsonToJS = map; | |
| 77 | + } | |
| 78 | + return typ.jsonToJS; | |
| 79 | +} | |
| 80 | + | |
| 81 | +function jsToJSONProps(typ: any): any { | |
| 82 | + if (typ.jsToJSON === undefined) { | |
| 83 | + const map: any = {}; | |
| 84 | + typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ }); | |
| 85 | + typ.jsToJSON = map; | |
| 86 | + } | |
| 87 | + return typ.jsToJSON; | |
| 88 | +} | |
| 89 | + | |
| 90 | +function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any { | |
| 91 | + function transformPrimitive(typ: string, val: any): any { | |
| 92 | + if (typeof typ === typeof val) return val; | |
| 93 | + return invalidValue(typ, val, key, parent); | |
| 94 | + } | |
| 95 | + | |
| 96 | + function transformUnion(typs: any[], val: any): any { | |
| 97 | + // val must validate against one typ in typs | |
| 98 | + const l = typs.length; | |
| 99 | + for (let i = 0; i < l; i++) { | |
| 100 | + const typ = typs[i]; | |
| 101 | + try { | |
| 102 | + return transform(val, typ, getProps); | |
| 103 | + } catch (_) {} | |
| 104 | + } | |
| 105 | + return invalidValue(typs, val, key, parent); | |
| 106 | + } | |
| 107 | + | |
| 108 | + function transformEnum(cases: string[], val: any): any { | |
| 109 | + if (cases.indexOf(val) !== -1) return val; | |
| 110 | + return invalidValue(cases.map(a => { return l(a); }), val, key, parent); | |
| 111 | + } | |
| 112 | + | |
| 113 | + function transformArray(typ: any, val: any): any { | |
| 114 | + // val must be an array with no invalid elements | |
| 115 | + if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent); | |
| 116 | + return val.map(el => transform(el, typ, getProps)); | |
| 117 | + } | |
| 118 | + | |
| 119 | + function transformDate(val: any): any { | |
| 120 | + if (val === null) { | |
| 121 | + return null; | |
| 122 | + } | |
| 123 | + const d = new Date(val); | |
| 124 | + if (isNaN(d.valueOf())) { | |
| 125 | + return invalidValue(l("Date"), val, key, parent); | |
| 126 | + } | |
| 127 | + return d; | |
| 128 | + } | |
| 129 | + | |
| 130 | + function transformObject(props: { [k: string]: any }, additional: any, val: any): any { | |
| 131 | + if (val === null || typeof val !== "object" || Array.isArray(val)) { | |
| 132 | + return invalidValue(l(ref || "object"), val, key, parent); | |
| 133 | + } | |
| 134 | + const result: any = {}; | |
| 135 | + Object.getOwnPropertyNames(props).forEach(key => { | |
| 136 | + const prop = props[key]; | |
| 137 | + const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined; | |
| 138 | + result[prop.key] = transform(v, prop.typ, getProps, key, ref); | |
| 139 | + }); | |
| 140 | + Object.getOwnPropertyNames(val).forEach(key => { | |
| 141 | + if (!Object.prototype.hasOwnProperty.call(props, key)) { | |
| 142 | + result[key] = transform(val[key], additional, getProps, key, ref); | |
| 143 | + } | |
| 144 | + }); | |
| 145 | + return result; | |
| 146 | + } | |
| 147 | + | |
| 148 | + if (typ === "any") return val; | |
| 149 | + if (typ === null) { | |
| 150 | + if (val === null) return val; | |
| 151 | + return invalidValue(typ, val, key, parent); | |
| 152 | + } | |
| 153 | + if (typ === false) return invalidValue(typ, val, key, parent); | |
| 154 | + let ref: any = undefined; | |
| 155 | + while (typeof typ === "object" && typ.ref !== undefined) { | |
| 156 | + ref = typ.ref; | |
| 157 | + typ = typeMap[typ.ref]; | |
| 158 | + } | |
| 159 | + if (Array.isArray(typ)) return transformEnum(typ, val); | |
| 160 | + if (typeof typ === "object") { | |
| 161 | + return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val) | |
| 162 | + : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val) | |
| 163 | + : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val) | |
| 164 | + : invalidValue(typ, val, key, parent); | |
| 165 | + } | |
| 166 | + // Numbers can be parsed by Date but shouldn't be. | |
| 167 | + if (typ === Date && typeof val !== "number") return transformDate(val); | |
| 168 | + return transformPrimitive(typ, val); | |
| 169 | +} | |
| 170 | + | |
| 171 | +function cast<T>(val: any, typ: any): T { | |
| 172 | + return transform(val, typ, jsonToJSProps); | |
| 173 | +} | |
| 174 | + | |
| 175 | +function uncast<T>(val: T, typ: any): any { | |
| 176 | + return transform(val, typ, jsToJSONProps); | |
| 177 | +} | |
| 178 | + | |
| 179 | +function l(typ: any) { | |
| 180 | + return { literal: typ }; | |
| 181 | +} | |
| 182 | + | |
| 183 | +function a(typ: any) { | |
| 184 | + return { arrayItems: typ }; | |
| 185 | +} | |
| 186 | + | |
| 187 | +function u(...typs: any[]) { | |
| 188 | + return { unionMembers: typs }; | |
| 189 | +} | |
| 190 | + | |
| 191 | +function o(props: any[], additional: any) { | |
| 192 | + return { props, additional }; | |
| 193 | +} | |
| 194 | + | |
| 195 | +function m(additional: any) { | |
| 196 | + const props: any[] = []; | |
| 197 | + return { props, additional }; | |
| 198 | +} | |
| 199 | + | |
| 200 | +function r(name: string) { | |
| 201 | + return { ref: name }; | |
| 202 | +} | |
| 203 | + | |
| 204 | +const typeMap: any = { | |
| 205 | + "TopLevel": o([ | |
| 206 | + { json: "waypoints", js: "waypoints", typ: u(undefined, a(r("SCUBAWaypoint"))) }, | |
| 207 | + ], "any"), | |
| 208 | + "SCUBAWaypoint": o([ | |
| 209 | + { json: "depth", js: "depth", typ: u(undefined, 3.14) }, | |
| 210 | + { json: "idCard", js: "idCard", typ: u(undefined, r("IDCardHTTP")) }, | |
| 211 | + { json: "location", js: "location", typ: u(undefined, r("Point")) }, | |
| 212 | + { json: "maneuver", js: "maneuver", typ: u(undefined, r("SCUBAManeuver")) }, | |
| 213 | + ], "any"), | |
| 214 | + "IDCardHTTP": o([ | |
| 215 | + { json: "value", js: "value", typ: u(undefined, "") }, | |
| 216 | + ], "any"), | |
| 217 | + "Point": o([ | |
| 218 | + { json: "latitude", js: "latitude", typ: u(undefined, 3.14) }, | |
| 219 | + { json: "longitude", js: "longitude", typ: u(undefined, 3.14) }, | |
| 220 | + ], "any"), | |
| 221 | + "SCUBAManeuver": [ | |
| 222 | + "ASCENT", | |
| 223 | + "DESCENT", | |
| 224 | + "LEVEL", | |
| 225 | + ], | |
| 226 | +}; |
No generated files match these filters.