Test case
2 generated files · +4 −0test/inputs/json/misc/ed095.json
Mflowdefault / TopLevel.js+2 −0
| @@ -9,6 +9,8 @@ | ||
| 9 | 9 | // These functions will throw an error if the JSON doesn't |
| 10 | 10 | // match the expected interface, even if the JSON is valid. |
| 11 | 11 | |
| 12 | +export type TopLevel = { [key: string]: string }; | |
| 13 | + | |
| 12 | 14 | // Converts JSON strings to/from your types |
| 13 | 15 | // and asserts the results of JSON.parse at runtime |
| 14 | 16 | function toTopLevel(json: string): { [key: string]: string } { |
Mtypescriptdefault / TopLevel.ts+2 −0
| @@ -7,6 +7,8 @@ | ||
| 7 | 7 | // These functions will throw an error if the JSON doesn't |
| 8 | 8 | // match the expected interface, even if the JSON is valid. |
| 9 | 9 | |
| 10 | +export type TopLevel = { [key: string]: string }; | |
| 11 | + | |
| 10 | 12 | // Converts JSON strings to/from your types |
| 11 | 13 | // and asserts the results of JSON.parse at runtime |
| 12 | 14 | export class Convert { |
Test case
2 generated files · +4 −0test/inputs/json/priority/issue2680-scalar-array.json
Mflowdefault / TopLevel.js+2 −0
| @@ -9,6 +9,8 @@ | ||
| 9 | 9 | // These functions will throw an error if the JSON doesn't |
| 10 | 10 | // match the expected interface, even if the JSON is valid. |
| 11 | 11 | |
| 12 | +export type TopLevel = number[]; | |
| 13 | + | |
| 12 | 14 | // Converts JSON strings to/from your types |
| 13 | 15 | // and asserts the results of JSON.parse at runtime |
| 14 | 16 | function toTopLevel(json: string): number[] { |
Mtypescriptdefault / TopLevel.ts+2 −0
| @@ -7,6 +7,8 @@ | ||
| 7 | 7 | // These functions will throw an error if the JSON doesn't |
| 8 | 8 | // match the expected interface, even if the JSON is valid. |
| 9 | 9 | |
| 10 | +export type TopLevel = number[]; | |
| 11 | + | |
| 10 | 12 | // Converts JSON strings to/from your types |
| 11 | 13 | // and asserts the results of JSON.parse at runtime |
| 12 | 14 | export class Convert { |
Test case
2 generated files · +2 −2test/inputs/json/priority/no-classes.json
Mflowdefault / TopLevel.js+1 −1
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | // These functions will throw an error if the JSON doesn't |
| 10 | 10 | // match the expected interface, even if the JSON is valid. |
| 11 | 11 | |
| 12 | -type TopLevel = number; | |
| 12 | +export type TopLevel = number; | |
| 13 | 13 | |
| 14 | 14 | // Converts JSON strings to/from your types |
| 15 | 15 | // and asserts the results of JSON.parse at runtime |
Mtypescriptdefault / TopLevel.ts+1 −1
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | // These functions will throw an error if the JSON doesn't |
| 8 | 8 | // match the expected interface, even if the JSON is valid. |
| 9 | 9 | |
| 10 | -type TopLevel = number; | |
| 10 | +export type TopLevel = number; | |
| 11 | 11 | |
| 12 | 12 | // Converts JSON strings to/from your types |
| 13 | 13 | // and asserts the results of JSON.parse at runtime |
Test case
29 generated files · +1,925 −0test/inputs/schema/empty-object.schema
Aschema-cjsondefault / TopLevel.c+87 −0
| @@ -0,0 +1,87 @@ | ||
| 1 | +/** | |
| 2 | + * TopLevel.c | |
| 3 | + * This file has been autogenerated using quicktype https://github.com/quicktype/quicktype - DO NOT EDIT | |
| 4 | + */ | |
| 5 | + | |
| 6 | +#include "TopLevel.h" | |
| 7 | + | |
| 8 | +struct TopLevel * cJSON_ParseTopLevel(const char * s) { | |
| 9 | + struct TopLevel * x = NULL; | |
| 10 | + if (NULL != s) { | |
| 11 | + cJSON * j = cJSON_Parse(s); | |
| 12 | + if (NULL != j) { | |
| 13 | + x = cJSON_GetTopLevelValue(j); | |
| 14 | + cJSON_Delete(j); | |
| 15 | + } | |
| 16 | + } | |
| 17 | + return x; | |
| 18 | +} | |
| 19 | + | |
| 20 | +struct TopLevel * cJSON_GetTopLevelValue(const cJSON * j) { | |
| 21 | + struct TopLevel * x = NULL; | |
| 22 | + if (NULL != j) { | |
| 23 | + if (NULL != (x = cJSON_malloc(sizeof(struct TopLevel)))) { | |
| 24 | + memset(x, 0, sizeof(struct TopLevel)); | |
| 25 | + x->value = hashtable_create(64, false); | |
| 26 | + if (NULL != x->value) { | |
| 27 | + cJSON * e = NULL; | |
| 28 | + cJSON_ArrayForEach(e, j) { | |
| 29 | + hashtable_add(x->value, e->string, (void *)0xDEADBEEF, sizeof(void *)); | |
| 30 | + } | |
| 31 | + } | |
| 32 | + } | |
| 33 | + } | |
| 34 | + return x; | |
| 35 | +} | |
| 36 | + | |
| 37 | +cJSON * cJSON_CreateTopLevel(const struct TopLevel * x) { | |
| 38 | + cJSON * j = NULL; | |
| 39 | + if (NULL != x) { | |
| 40 | + if (NULL != x->value) { | |
| 41 | + j = cJSON_CreateObject(); | |
| 42 | + if (NULL != j) { | |
| 43 | + char **keys = NULL; | |
| 44 | + size_t count = hashtable_get_keys(x->value, &keys); | |
| 45 | + if (NULL != keys) { | |
| 46 | + for (size_t index = 0; index < count; index++) { | |
| 47 | + void *x2 = hashtable_lookup(x->value, keys[index]); | |
| 48 | + } | |
| 49 | + cJSON_free(keys); | |
| 50 | + } | |
| 51 | + } | |
| 52 | + } | |
| 53 | + } | |
| 54 | + return j; | |
| 55 | +} | |
| 56 | + | |
| 57 | +char * cJSON_PrintTopLevel(const struct TopLevel * x) { | |
| 58 | + char * s = NULL; | |
| 59 | + if (NULL != x) { | |
| 60 | + cJSON * j = cJSON_CreateTopLevel(x); | |
| 61 | + if (NULL != j) { | |
| 62 | + s = cJSON_Print(j); | |
| 63 | + cJSON_Delete(j); | |
| 64 | + } | |
| 65 | + } | |
| 66 | + return s; | |
| 67 | +} | |
| 68 | + | |
| 69 | +void cJSON_DeleteTopLevel(struct TopLevel * x) { | |
| 70 | + if (NULL != x) { | |
| 71 | + if (NULL != x->value) { | |
| 72 | + char **keys = NULL; | |
| 73 | + size_t count = hashtable_get_keys(x->value, &keys); | |
| 74 | + if (NULL != keys) { | |
| 75 | + for (size_t index = 0; index < count; index++) { | |
| 76 | + void *x2 = hashtable_lookup(x->value, keys[index]); | |
| 77 | + if (NULL != x2) { | |
| 78 | + (x2); | |
| 79 | + } | |
| 80 | + } | |
| 81 | + cJSON_free(keys); | |
| 82 | + } | |
| 83 | + hashtable_release(x->value); | |
| 84 | + } | |
| 85 | + cJSON_free(x); | |
| 86 | + } | |
| 87 | +} |
Aschema-cjsondefault / TopLevel.h+51 −0
| @@ -0,0 +1,51 @@ | ||
| 1 | +/** | |
| 2 | + * TopLevel.h | |
| 3 | + * This file has been autogenerated using quicktype https://github.com/quicktype/quicktype - DO NOT EDIT | |
| 4 | + * This file depends of https://github.com/DaveGamble/cJSON, https://github.com/joelguittet/c-list and https://github.com/joelguittet/c-hashtable | |
| 5 | + * To parse json data from json string use the following: struct <type> * data = cJSON_Parse<type>(<string>); | |
| 6 | + * To get json data from cJSON object use the following: struct <type> * data = cJSON_Get<type>Value(<cjson>); | |
| 7 | + * To get cJSON object from json data use the following: cJSON * cjson = cJSON_Create<type>(<data>); | |
| 8 | + * To print json string from json data use the following: char * string = cJSON_Print<type>(<data>); | |
| 9 | + * To delete json data use the following: cJSON_Delete<type>(<data>); | |
| 10 | + */ | |
| 11 | + | |
| 12 | +#ifndef __TOPLEVEL_H__ | |
| 13 | +#define __TOPLEVEL_H__ | |
| 14 | + | |
| 15 | +#ifdef __cplusplus | |
| 16 | +extern "C" { | |
| 17 | +#endif | |
| 18 | + | |
| 19 | +#include <stdint.h> | |
| 20 | +#include <stdbool.h> | |
| 21 | +#include <stdlib.h> | |
| 22 | +#include <string.h> | |
| 23 | +#include <cJSON.h> | |
| 24 | +#include <hashtable.h> | |
| 25 | +#include <list.h> | |
| 26 | + | |
| 27 | +#ifndef cJSON_Bool | |
| 28 | +#define cJSON_Bool (cJSON_True | cJSON_False) | |
| 29 | +#endif | |
| 30 | +#ifndef cJSON_Map | |
| 31 | +#define cJSON_Map (1 << 16) | |
| 32 | +#endif | |
| 33 | +#ifndef cJSON_Enum | |
| 34 | +#define cJSON_Enum (1 << 17) | |
| 35 | +#endif | |
| 36 | + | |
| 37 | +struct TopLevel { | |
| 38 | + hashtable_t * value; | |
| 39 | +}; | |
| 40 | + | |
| 41 | +struct TopLevel * cJSON_ParseTopLevel(const char * s); | |
| 42 | +struct TopLevel * cJSON_GetTopLevelValue(const cJSON * j); | |
| 43 | +cJSON * cJSON_CreateTopLevel(const struct TopLevel * x); | |
| 44 | +char * cJSON_PrintTopLevel(const struct TopLevel * x); | |
| 45 | +void cJSON_DeleteTopLevel(struct TopLevel * x); | |
| 46 | + | |
| 47 | +#ifdef __cplusplus | |
| 48 | +} | |
| 49 | +#endif | |
| 50 | + | |
| 51 | +#endif /* __TOPLEVEL_H__ */ |
Aschema-cplusplusdefault / quicktype.hpp+35 −0
| @@ -0,0 +1,35 @@ | ||
| 1 | +// To parse this JSON data, first install | |
| 2 | +// | |
| 3 | +// json.hpp https://github.com/nlohmann/json | |
| 4 | +// | |
| 5 | +// Then include this file, and then do | |
| 6 | +// | |
| 7 | +// TopLevel data = nlohmann::json::parse(jsonString); | |
| 8 | + | |
| 9 | +#pragma once | |
| 10 | + | |
| 11 | +#include "json.hpp" | |
| 12 | + | |
| 13 | +#include <optional> | |
| 14 | +#include <stdexcept> | |
| 15 | +#include <regex> | |
| 16 | + | |
| 17 | +namespace quicktype { | |
| 18 | + using nlohmann::json; | |
| 19 | + | |
| 20 | + #ifndef NLOHMANN_UNTYPED_quicktype_HELPER | |
| 21 | + #define NLOHMANN_UNTYPED_quicktype_HELPER | |
| 22 | + inline json get_untyped(const json & j, const char * property) { | |
| 23 | + if (j.find(property) != j.end()) { | |
| 24 | + return j.at(property).get<json>(); | |
| 25 | + } | |
| 26 | + return json(); | |
| 27 | + } | |
| 28 | + | |
| 29 | + inline json get_untyped(const json & j, std::string property) { | |
| 30 | + return get_untyped(j, property.data()); | |
| 31 | + } | |
| 32 | + #endif | |
| 33 | + | |
| 34 | + using TopLevel = std::map<std::string, nlohmann::json>; | |
| 35 | +} |
Aschema-csharp-recordsdefault / QuickType.cs+55 −0
| @@ -0,0 +1,55 @@ | ||
| 1 | +// <auto-generated /> | |
| 2 | +// | |
| 3 | +// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do: | |
| 4 | +// | |
| 5 | +// using QuickType; | |
| 6 | +// | |
| 7 | +// var topLevel = TopLevel.FromJson(jsonString); | |
| 8 | +#nullable enable | |
| 9 | +#pragma warning disable CS8618 | |
| 10 | +#pragma warning disable CS8601 | |
| 11 | +#pragma warning disable CS8602 | |
| 12 | +#pragma warning disable CS8603 | |
| 13 | +#pragma warning disable CS8604 | |
| 14 | +#pragma warning disable CS8625 | |
| 15 | +#pragma warning disable CS8765 | |
| 16 | + | |
| 17 | +namespace QuickType | |
| 18 | +{ | |
| 19 | + using System; | |
| 20 | + using System.Collections.Generic; | |
| 21 | + | |
| 22 | + using System.Globalization; | |
| 23 | + using Newtonsoft.Json; | |
| 24 | + using Newtonsoft.Json.Converters; | |
| 25 | + | |
| 26 | + public class TopLevel | |
| 27 | + { | |
| 28 | + public static Dictionary<string, object> FromJson(string json) => JsonConvert.DeserializeObject<Dictionary<string, object>>(json, QuickType.Converter.Settings); | |
| 29 | + } | |
| 30 | + | |
| 31 | + public static partial class Serialize | |
| 32 | + { | |
| 33 | + public static string ToJson(this Dictionary<string, object> self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings); | |
| 34 | + } | |
| 35 | + | |
| 36 | + internal static partial class Converter | |
| 37 | + { | |
| 38 | + public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings | |
| 39 | + { | |
| 40 | + MetadataPropertyHandling = MetadataPropertyHandling.Ignore, | |
| 41 | + DateParseHandling = DateParseHandling.None, | |
| 42 | + Converters = | |
| 43 | + { | |
| 44 | + new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal } | |
| 45 | + }, | |
| 46 | + }; | |
| 47 | + } | |
| 48 | +} | |
| 49 | +#pragma warning restore CS8618 | |
| 50 | +#pragma warning restore CS8601 | |
| 51 | +#pragma warning restore CS8602 | |
| 52 | +#pragma warning restore CS8603 | |
| 53 | +#pragma warning restore CS8604 | |
| 54 | +#pragma warning restore CS8625 | |
| 55 | +#pragma warning restore CS8765 |
Aschema-csharp-SystemTextJsondefault / QuickType.cs+159 −0
| @@ -0,0 +1,159 @@ | ||
| 1 | +// <auto-generated /> | |
| 2 | +// | |
| 3 | +// To parse this JSON data, add NuGet 'System.Text.Json' then do: | |
| 4 | +// | |
| 5 | +// using QuickType; | |
| 6 | +// | |
| 7 | +// var topLevel = TopLevel.FromJson(jsonString); | |
| 8 | +#nullable enable | |
| 9 | +#pragma warning disable CS8618 | |
| 10 | +#pragma warning disable CS8601 | |
| 11 | +#pragma warning disable CS8602 | |
| 12 | +#pragma warning disable CS8603 | |
| 13 | + | |
| 14 | +namespace QuickType | |
| 15 | +{ | |
| 16 | + using System; | |
| 17 | + using System.Collections.Generic; | |
| 18 | + | |
| 19 | + using System.Text.Json; | |
| 20 | + using System.Text.Json.Serialization; | |
| 21 | + using System.Globalization; | |
| 22 | + | |
| 23 | + public class TopLevel | |
| 24 | + { | |
| 25 | + public static Dictionary<string, object> FromJson(string json) => JsonSerializer.Deserialize<Dictionary<string, object>>(json, QuickType.Converter.Settings); | |
| 26 | + } | |
| 27 | + | |
| 28 | + public static partial class Serialize | |
| 29 | + { | |
| 30 | + public static string ToJson(this Dictionary<string, object> self) => JsonSerializer.Serialize(self, QuickType.Converter.Settings); | |
| 31 | + } | |
| 32 | + | |
| 33 | + internal static partial class Converter | |
| 34 | + { | |
| 35 | + public static readonly JsonSerializerOptions Settings = new(JsonSerializerDefaults.General) | |
| 36 | + { | |
| 37 | + Converters = | |
| 38 | + { | |
| 39 | + new DateOnlyConverter(), | |
| 40 | + new TimeOnlyConverter(), | |
| 41 | + IsoDateTimeOffsetConverter.Singleton | |
| 42 | + }, | |
| 43 | + }; | |
| 44 | + } | |
| 45 | + | |
| 46 | + public class DateOnlyConverter : JsonConverter<DateOnly> | |
| 47 | + { | |
| 48 | + private readonly string serializationFormat; | |
| 49 | + public DateOnlyConverter() : this(null) { } | |
| 50 | + | |
| 51 | + public DateOnlyConverter(string? serializationFormat) | |
| 52 | + { | |
| 53 | + this.serializationFormat = serializationFormat ?? "yyyy-MM-dd"; | |
| 54 | + } | |
| 55 | + | |
| 56 | + public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
| 57 | + { | |
| 58 | + var value = reader.GetString(); | |
| 59 | + return DateOnly.Parse(value!); | |
| 60 | + } | |
| 61 | + | |
| 62 | + public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options) | |
| 63 | + => writer.WriteStringValue(value.ToString(serializationFormat)); | |
| 64 | + } | |
| 65 | + | |
| 66 | + public class TimeOnlyConverter : JsonConverter<TimeOnly> | |
| 67 | + { | |
| 68 | + private readonly string serializationFormat; | |
| 69 | + | |
| 70 | + public TimeOnlyConverter() : this(null) { } | |
| 71 | + | |
| 72 | + public TimeOnlyConverter(string? serializationFormat) | |
| 73 | + { | |
| 74 | + this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff"; | |
| 75 | + } | |
| 76 | + | |
| 77 | + public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
| 78 | + { | |
| 79 | + var value = reader.GetString(); | |
| 80 | + return TimeOnly.Parse(value!); | |
| 81 | + } | |
| 82 | + | |
| 83 | + public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options) | |
| 84 | + => writer.WriteStringValue(value.ToString(serializationFormat)); | |
| 85 | + } | |
| 86 | + | |
| 87 | + internal class IsoDateTimeOffsetConverter : JsonConverter<DateTimeOffset> | |
| 88 | + { | |
| 89 | + public override bool CanConvert(Type t) => t == typeof(DateTimeOffset); | |
| 90 | + | |
| 91 | + private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; | |
| 92 | + | |
| 93 | + private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind; | |
| 94 | + private string? _dateTimeFormat; | |
| 95 | + private CultureInfo? _culture; | |
| 96 | + | |
| 97 | + public DateTimeStyles DateTimeStyles | |
| 98 | + { | |
| 99 | + get => _dateTimeStyles; | |
| 100 | + set => _dateTimeStyles = value; | |
| 101 | + } | |
| 102 | + | |
| 103 | + public string? DateTimeFormat | |
| 104 | + { | |
| 105 | + get => _dateTimeFormat ?? string.Empty; | |
| 106 | + set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value; | |
| 107 | + } | |
| 108 | + | |
| 109 | + public CultureInfo Culture | |
| 110 | + { | |
| 111 | + get => _culture ?? CultureInfo.CurrentCulture; | |
| 112 | + set => _culture = value; | |
| 113 | + } | |
| 114 | + | |
| 115 | + public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options) | |
| 116 | + { | |
| 117 | + string text; | |
| 118 | + | |
| 119 | + | |
| 120 | + if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal | |
| 121 | + || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal) | |
| 122 | + { | |
| 123 | + value = value.ToUniversalTime(); | |
| 124 | + } | |
| 125 | + | |
| 126 | + text = value.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture); | |
| 127 | + | |
| 128 | + writer.WriteStringValue(text); | |
| 129 | + } | |
| 130 | + | |
| 131 | + public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
| 132 | + { | |
| 133 | + string? dateText = reader.GetString(); | |
| 134 | + | |
| 135 | + if (string.IsNullOrEmpty(dateText) == false) | |
| 136 | + { | |
| 137 | + if (!string.IsNullOrEmpty(_dateTimeFormat)) | |
| 138 | + { | |
| 139 | + return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles); | |
| 140 | + } | |
| 141 | + else | |
| 142 | + { | |
| 143 | + return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles); | |
| 144 | + } | |
| 145 | + } | |
| 146 | + else | |
| 147 | + { | |
| 148 | + return default(DateTimeOffset); | |
| 149 | + } | |
| 150 | + } | |
| 151 | + | |
| 152 | + | |
| 153 | + public static readonly IsoDateTimeOffsetConverter Singleton = new IsoDateTimeOffsetConverter(); | |
| 154 | + } | |
| 155 | +} | |
| 156 | +#pragma warning restore CS8618 | |
| 157 | +#pragma warning restore CS8601 | |
| 158 | +#pragma warning restore CS8602 | |
| 159 | +#pragma warning restore CS8603 |
Aschema-csharpdefault / QuickType.cs+55 −0
| @@ -0,0 +1,55 @@ | ||
| 1 | +// <auto-generated /> | |
| 2 | +// | |
| 3 | +// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do: | |
| 4 | +// | |
| 5 | +// using QuickType; | |
| 6 | +// | |
| 7 | +// var topLevel = TopLevel.FromJson(jsonString); | |
| 8 | +#nullable enable | |
| 9 | +#pragma warning disable CS8618 | |
| 10 | +#pragma warning disable CS8601 | |
| 11 | +#pragma warning disable CS8602 | |
| 12 | +#pragma warning disable CS8603 | |
| 13 | +#pragma warning disable CS8604 | |
| 14 | +#pragma warning disable CS8625 | |
| 15 | +#pragma warning disable CS8765 | |
| 16 | + | |
| 17 | +namespace QuickType | |
| 18 | +{ | |
| 19 | + using System; | |
| 20 | + using System.Collections.Generic; | |
| 21 | + | |
| 22 | + using System.Globalization; | |
| 23 | + using Newtonsoft.Json; | |
| 24 | + using Newtonsoft.Json.Converters; | |
| 25 | + | |
| 26 | + public class TopLevel | |
| 27 | + { | |
| 28 | + public static Dictionary<string, object> FromJson(string json) => JsonConvert.DeserializeObject<Dictionary<string, object>>(json, QuickType.Converter.Settings); | |
| 29 | + } | |
| 30 | + | |
| 31 | + public static partial class Serialize | |
| 32 | + { | |
| 33 | + public static string ToJson(this Dictionary<string, object> self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings); | |
| 34 | + } | |
| 35 | + | |
| 36 | + internal static partial class Converter | |
| 37 | + { | |
| 38 | + public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings | |
| 39 | + { | |
| 40 | + MetadataPropertyHandling = MetadataPropertyHandling.Ignore, | |
| 41 | + DateParseHandling = DateParseHandling.None, | |
| 42 | + Converters = | |
| 43 | + { | |
| 44 | + new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal } | |
| 45 | + }, | |
| 46 | + }; | |
| 47 | + } | |
| 48 | +} | |
| 49 | +#pragma warning restore CS8618 | |
| 50 | +#pragma warning restore CS8601 | |
| 51 | +#pragma warning restore CS8602 | |
| 52 | +#pragma warning restore CS8603 | |
| 53 | +#pragma warning restore CS8604 | |
| 54 | +#pragma warning restore CS8625 | |
| 55 | +#pragma warning restore CS8765 |
Aschema-dartdefault / TopLevel.dart+9 −0
| @@ -0,0 +1,9 @@ | ||
| 1 | +// To parse this JSON data, do | |
| 2 | +// | |
| 3 | +// final topLevel = topLevelFromJson(jsonString); | |
| 4 | + | |
| 5 | +import 'dart:convert'; | |
| 6 | + | |
| 7 | +Map<String, dynamic> topLevelFromJson(String str) => Map.from(json.decode(str)).map((k, v) => MapEntry<String, dynamic>(k, v)); | |
| 8 | + | |
| 9 | +String topLevelToJson(Map<String, dynamic> data) => json.encode(Map.from(data).map((k, v) => MapEntry<String, dynamic>(k, v))); |
Aschema-elmdefault / QuickType.elm+41 −0
| @@ -0,0 +1,41 @@ | ||
| 1 | +-- To decode the JSON data, add this file to your project, run | |
| 2 | +-- | |
| 3 | +-- elm install NoRedInk/elm-json-decode-pipeline | |
| 4 | +-- | |
| 5 | +-- add these imports | |
| 6 | +-- | |
| 7 | +-- import Json.Decode exposing (decodeString) | |
| 8 | +-- import QuickType exposing (quickType) | |
| 9 | +-- | |
| 10 | +-- and you're off to the races with | |
| 11 | +-- | |
| 12 | +-- decodeString quickType myJsonString | |
| 13 | + | |
| 14 | +module QuickType exposing | |
| 15 | + ( QuickType | |
| 16 | + , quickTypeToString | |
| 17 | + , quickType | |
| 18 | + ) | |
| 19 | + | |
| 20 | +import Json.Decode as Jdec | |
| 21 | +import Json.Decode.Pipeline as Jpipe | |
| 22 | +import Json.Encode as Jenc | |
| 23 | +import Dict exposing (Dict) | |
| 24 | + | |
| 25 | +type alias QuickType = Dict String Jdec.Value | |
| 26 | + | |
| 27 | +-- decoders and encoders | |
| 28 | + | |
| 29 | +quickType : Jdec.Decoder QuickType | |
| 30 | +quickType = Jdec.dict Jdec.value | |
| 31 | + | |
| 32 | +quickTypeToString : QuickType -> String | |
| 33 | +quickTypeToString r = Jenc.encode 0 (Jenc.dict identity identity r) | |
| 34 | + | |
| 35 | +--- encoder helpers | |
| 36 | + | |
| 37 | +makeNullableEncoder : (a -> Jenc.Value) -> Maybe a -> Jenc.Value | |
| 38 | +makeNullableEncoder f m = | |
| 39 | + case m of | |
| 40 | + Just x -> f x | |
| 41 | + Nothing -> Jenc.null |
Aschema-flowdefault / TopLevel.js+183 −0
| @@ -0,0 +1,183 @@ | ||
| 1 | +// @flow | |
| 2 | + | |
| 3 | +// To parse this data: | |
| 4 | +// | |
| 5 | +// const Convert = require("./TopLevel"); | |
| 6 | +// | |
| 7 | +// const topLevel = Convert.toTopLevel(json); | |
| 8 | +// | |
| 9 | +// These functions will throw an error if the JSON doesn't | |
| 10 | +// match the expected interface, even if the JSON is valid. | |
| 11 | + | |
| 12 | +export type TopLevel = { [key: string]: mixed }; | |
| 13 | + | |
| 14 | +// Converts JSON strings to/from your types | |
| 15 | +// and asserts the results of JSON.parse at runtime | |
| 16 | +function toTopLevel(json: string): { [key: string]: mixed } { | |
| 17 | + return cast(JSON.parse(json), m("any")); | |
| 18 | +} | |
| 19 | + | |
| 20 | +function topLevelToJson(value: { [key: string]: mixed }): string { | |
| 21 | + return JSON.stringify(uncast(value, m("any")), null, 2); | |
| 22 | +} | |
| 23 | + | |
| 24 | +function invalidValue(typ: any, val: any, key: any, parent: any = '') { | |
| 25 | + const prettyTyp = prettyTypeName(typ); | |
| 26 | + const parentText = parent ? ` on ${parent}` : ''; | |
| 27 | + const keyText = key ? ` for key "${key}"` : ''; | |
| 28 | + throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`); | |
| 29 | +} | |
| 30 | + | |
| 31 | +function prettyTypeName(typ: any): string { | |
| 32 | + if (Array.isArray(typ)) { | |
| 33 | + if (typ.length === 2 && typ[0] === undefined) { | |
| 34 | + return `an optional ${prettyTypeName(typ[1])}`; | |
| 35 | + } else { | |
| 36 | + return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`; | |
| 37 | + } | |
| 38 | + } else if (typeof typ === "object" && typ.literal !== undefined) { | |
| 39 | + return typ.literal; | |
| 40 | + } else { | |
| 41 | + return typeof typ; | |
| 42 | + } | |
| 43 | +} | |
| 44 | + | |
| 45 | +function jsonToJSProps(typ: any): any { | |
| 46 | + if (typ.jsonToJS === undefined) { | |
| 47 | + const map: any = {}; | |
| 48 | + typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ }); | |
| 49 | + typ.jsonToJS = map; | |
| 50 | + } | |
| 51 | + return typ.jsonToJS; | |
| 52 | +} | |
| 53 | + | |
| 54 | +function jsToJSONProps(typ: any): any { | |
| 55 | + if (typ.jsToJSON === undefined) { | |
| 56 | + const map: any = {}; | |
| 57 | + typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ }); | |
| 58 | + typ.jsToJSON = map; | |
| 59 | + } | |
| 60 | + return typ.jsToJSON; | |
| 61 | +} | |
| 62 | + | |
| 63 | +function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any { | |
| 64 | + function transformPrimitive(typ: string, val: any): any { | |
| 65 | + if (typeof typ === typeof val) return val; | |
| 66 | + return invalidValue(typ, val, key, parent); | |
| 67 | + } | |
| 68 | + | |
| 69 | + function transformUnion(typs: any[], val: any): any { | |
| 70 | + // val must validate against one typ in typs | |
| 71 | + const l = typs.length; | |
| 72 | + for (let i = 0; i < l; i++) { | |
| 73 | + const typ = typs[i]; | |
| 74 | + try { | |
| 75 | + return transform(val, typ, getProps); | |
| 76 | + } catch (_) {} | |
| 77 | + } | |
| 78 | + return invalidValue(typs, val, key, parent); | |
| 79 | + } | |
| 80 | + | |
| 81 | + function transformEnum(cases: string[], val: any): any { | |
| 82 | + if (cases.indexOf(val) !== -1) return val; | |
| 83 | + return invalidValue(cases.map(a => { return l(a); }), val, key, parent); | |
| 84 | + } | |
| 85 | + | |
| 86 | + function transformArray(typ: any, val: any): any { | |
| 87 | + // val must be an array with no invalid elements | |
| 88 | + if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent); | |
| 89 | + return val.map(el => transform(el, typ, getProps)); | |
| 90 | + } | |
| 91 | + | |
| 92 | + function transformDate(val: any): any { | |
| 93 | + if (val === null) { | |
| 94 | + return null; | |
| 95 | + } | |
| 96 | + const d = new Date(val); | |
| 97 | + if (isNaN(d.valueOf())) { | |
| 98 | + return invalidValue(l("Date"), val, key, parent); | |
| 99 | + } | |
| 100 | + return d; | |
| 101 | + } | |
| 102 | + | |
| 103 | + function transformObject(props: { [k: string]: any }, additional: any, val: any): any { | |
| 104 | + if (val === null || typeof val !== "object" || Array.isArray(val)) { | |
| 105 | + return invalidValue(l(ref || "object"), val, key, parent); | |
| 106 | + } | |
| 107 | + const result: any = {}; | |
| 108 | + Object.getOwnPropertyNames(props).forEach(key => { | |
| 109 | + const prop = props[key]; | |
| 110 | + const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined; | |
| 111 | + result[prop.key] = transform(v, prop.typ, getProps, key, ref); | |
| 112 | + }); | |
| 113 | + Object.getOwnPropertyNames(val).forEach(key => { | |
| 114 | + if (!Object.prototype.hasOwnProperty.call(props, key)) { | |
| 115 | + result[key] = transform(val[key], additional, getProps, key, ref); | |
| 116 | + } | |
| 117 | + }); | |
| 118 | + return result; | |
| 119 | + } | |
| 120 | + | |
| 121 | + if (typ === "any") return val; | |
| 122 | + if (typ === null) { | |
| 123 | + if (val === null) return val; | |
| 124 | + return invalidValue(typ, val, key, parent); | |
| 125 | + } | |
| 126 | + if (typ === false) return invalidValue(typ, val, key, parent); | |
| 127 | + let ref: any = undefined; | |
| 128 | + while (typeof typ === "object" && typ.ref !== undefined) { | |
| 129 | + ref = typ.ref; | |
| 130 | + typ = typeMap[typ.ref]; | |
| 131 | + } | |
| 132 | + if (Array.isArray(typ)) return transformEnum(typ, val); | |
| 133 | + if (typeof typ === "object") { | |
| 134 | + return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val) | |
| 135 | + : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val) | |
| 136 | + : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val) | |
| 137 | + : invalidValue(typ, val, key, parent); | |
| 138 | + } | |
| 139 | + // Numbers can be parsed by Date but shouldn't be. | |
| 140 | + if (typ === Date && typeof val !== "number") return transformDate(val); | |
| 141 | + return transformPrimitive(typ, val); | |
| 142 | +} | |
| 143 | + | |
| 144 | +function cast<T>(val: any, typ: any): T { | |
| 145 | + return transform(val, typ, jsonToJSProps); | |
| 146 | +} | |
| 147 | + | |
| 148 | +function uncast<T>(val: T, typ: any): any { | |
| 149 | + return transform(val, typ, jsToJSONProps); | |
| 150 | +} | |
| 151 | + | |
| 152 | +function l(typ: any) { | |
| 153 | + return { literal: typ }; | |
| 154 | +} | |
| 155 | + | |
| 156 | +function a(typ: any) { | |
| 157 | + return { arrayItems: typ }; | |
| 158 | +} | |
| 159 | + | |
| 160 | +function u(...typs: any[]) { | |
| 161 | + return { unionMembers: typs }; | |
| 162 | +} | |
| 163 | + | |
| 164 | +function o(props: any[], additional: any) { | |
| 165 | + return { props, additional }; | |
| 166 | +} | |
| 167 | + | |
| 168 | +function m(additional: any) { | |
| 169 | + const props: any[] = []; | |
| 170 | + return { props, additional }; | |
| 171 | +} | |
| 172 | + | |
| 173 | +function r(name: string) { | |
| 174 | + return { ref: name }; | |
| 175 | +} | |
| 176 | + | |
| 177 | +const typeMap: any = { | |
| 178 | +}; | |
| 179 | + | |
| 180 | +module.exports = { | |
| 181 | + "topLevelToJson": topLevelToJson, | |
| 182 | + "toTopLevel": toTopLevel, | |
| 183 | +}; |
Aschema-golangdefault / quicktype.go+21 −0
| @@ -0,0 +1,21 @@ | ||
| 1 | +// Code generated from JSON Schema using quicktype. DO NOT EDIT. | |
| 2 | +// To parse and unparse this JSON data, add this code to your project and do: | |
| 3 | +// | |
| 4 | +// topLevel, err := UnmarshalTopLevel(bytes) | |
| 5 | +// bytes, err = topLevel.Marshal() | |
| 6 | + | |
| 7 | +package main | |
| 8 | + | |
| 9 | +import "encoding/json" | |
| 10 | + | |
| 11 | +type TopLevel map[string]interface{} | |
| 12 | + | |
| 13 | +func UnmarshalTopLevel(data []byte) (TopLevel, error) { | |
| 14 | + var r TopLevel | |
| 15 | + err := json.Unmarshal(data, &r) | |
| 16 | + return r, err | |
| 17 | +} | |
| 18 | + | |
| 19 | +func (r *TopLevel) Marshal() ([]byte, error) { | |
| 20 | + return json.Marshal(r) | |
| 21 | +} |
Aschema-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 | +// Map<String, Object> 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 Map<String, Object> fromJsonString(String json) throws IOException { | |
| 70 | + return getObjectReader().readValue(json); | |
| 71 | + } | |
| 72 | + | |
| 73 | + public static String toJsonString(Map<String, Object> 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(Map.class); | |
| 109 | + writer = mapper.writerFor(Map.class); | |
| 110 | + } | |
| 111 | + | |
| 112 | + private static ObjectReader getObjectReader() { | |
| 113 | + if (reader == null) instantiateMapper(); | |
| 114 | + return reader; | |
| 115 | + } | |
| 116 | + | |
| 117 | + private static ObjectWriter getObjectWriter() { | |
| 118 | + if (writer == null) instantiateMapper(); | |
| 119 | + return writer; | |
| 120 | + } | |
| 121 | +} |
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / TopLevel.java+4 −0
| @@ -0,0 +1,4 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +public class TopLevel { | |
| 4 | +} |
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 | +// Map<String, Object> 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 Map<String, Object> fromJsonString(String json) throws IOException { | |
| 64 | + return getObjectReader().readValue(json); | |
| 65 | + } | |
| 66 | + | |
| 67 | + public static String toJsonString(Map<String, Object> 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(Map.class); | |
| 89 | + writer = mapper.writerFor(Map.class); | |
| 90 | + } | |
| 91 | + | |
| 92 | + private static ObjectReader getObjectReader() { | |
| 93 | + if (reader == null) instantiateMapper(); | |
| 94 | + return reader; | |
| 95 | + } | |
| 96 | + | |
| 97 | + private static ObjectWriter getObjectWriter() { | |
| 98 | + if (writer == null) instantiateMapper(); | |
| 99 | + return writer; | |
| 100 | + } | |
| 101 | +} |
Aschema-java-lombokdefault / src / main / java / io / quicktype / TopLevel.java+4 −0
| @@ -0,0 +1,4 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +public class TopLevel { | |
| 4 | +} |
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 | +// Map<String, Object> 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 Map<String, Object> fromJsonString(String json) throws IOException { | |
| 64 | + return getObjectReader().readValue(json); | |
| 65 | + } | |
| 66 | + | |
| 67 | + public static String toJsonString(Map<String, Object> 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(Map.class); | |
| 89 | + writer = mapper.writerFor(Map.class); | |
| 90 | + } | |
| 91 | + | |
| 92 | + private static ObjectReader getObjectReader() { | |
| 93 | + if (reader == null) instantiateMapper(); | |
| 94 | + return reader; | |
| 95 | + } | |
| 96 | + | |
| 97 | + private static ObjectWriter getObjectWriter() { | |
| 98 | + if (writer == null) instantiateMapper(); | |
| 99 | + return writer; | |
| 100 | + } | |
| 101 | +} |
Aschema-javadefault / src / main / java / io / quicktype / TopLevel.java+4 −0
| @@ -0,0 +1,4 @@ | ||
| 1 | +package io.quicktype; | |
| 2 | + | |
| 3 | +public class TopLevel { | |
| 4 | +} |
Aschema-javascriptdefault / TopLevel.js+179 −0
| @@ -0,0 +1,179 @@ | ||
| 1 | +// To parse this data: | |
| 2 | +// | |
| 3 | +// const Convert = require("./TopLevel"); | |
| 4 | +// | |
| 5 | +// const topLevel = Convert.toTopLevel(json); | |
| 6 | +// | |
| 7 | +// These functions will throw an error if the JSON doesn't | |
| 8 | +// match the expected interface, even if the JSON is valid. | |
| 9 | + | |
| 10 | +// Converts JSON strings to/from your types | |
| 11 | +// and asserts the results of JSON.parse at runtime | |
| 12 | +function toTopLevel(json) { | |
| 13 | + return cast(JSON.parse(json), m("any")); | |
| 14 | +} | |
| 15 | + | |
| 16 | +function topLevelToJson(value) { | |
| 17 | + return JSON.stringify(uncast(value, m("any")), null, 2); | |
| 18 | +} | |
| 19 | + | |
| 20 | +function invalidValue(typ, val, key, parent = '') { | |
| 21 | + const prettyTyp = prettyTypeName(typ); | |
| 22 | + const parentText = parent ? ` on ${parent}` : ''; | |
| 23 | + const keyText = key ? ` for key "${key}"` : ''; | |
| 24 | + throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`); | |
| 25 | +} | |
| 26 | + | |
| 27 | +function prettyTypeName(typ) { | |
| 28 | + if (Array.isArray(typ)) { | |
| 29 | + if (typ.length === 2 && typ[0] === undefined) { | |
| 30 | + return `an optional ${prettyTypeName(typ[1])}`; | |
| 31 | + } else { | |
| 32 | + return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`; | |
| 33 | + } | |
| 34 | + } else if (typeof typ === "object" && typ.literal !== undefined) { | |
| 35 | + return typ.literal; | |
| 36 | + } else { | |
| 37 | + return typeof typ; | |
| 38 | + } | |
| 39 | +} | |
| 40 | + | |
| 41 | +function jsonToJSProps(typ) { | |
| 42 | + if (typ.jsonToJS === undefined) { | |
| 43 | + const map = {}; | |
| 44 | + typ.props.forEach((p) => map[p.json] = { key: p.js, typ: p.typ }); | |
| 45 | + typ.jsonToJS = map; | |
| 46 | + } | |
| 47 | + return typ.jsonToJS; | |
| 48 | +} | |
| 49 | + | |
| 50 | +function jsToJSONProps(typ) { | |
| 51 | + if (typ.jsToJSON === undefined) { | |
| 52 | + const map = {}; | |
| 53 | + typ.props.forEach((p) => map[p.js] = { key: p.json, typ: p.typ }); | |
| 54 | + typ.jsToJSON = map; | |
| 55 | + } | |
| 56 | + return typ.jsToJSON; | |
| 57 | +} | |
| 58 | + | |
| 59 | +function transform(val, typ, getProps, key = '', parent = '') { | |
| 60 | + function transformPrimitive(typ, val) { | |
| 61 | + if (typeof typ === typeof val) return val; | |
| 62 | + return invalidValue(typ, val, key, parent); | |
| 63 | + } | |
| 64 | + | |
| 65 | + function transformUnion(typs, val) { | |
| 66 | + // val must validate against one typ in typs | |
| 67 | + const l = typs.length; | |
| 68 | + for (let i = 0; i < l; i++) { | |
| 69 | + const typ = typs[i]; | |
| 70 | + try { | |
| 71 | + return transform(val, typ, getProps); | |
| 72 | + } catch (_) {} | |
| 73 | + } | |
| 74 | + return invalidValue(typs, val, key, parent); | |
| 75 | + } | |
| 76 | + | |
| 77 | + function transformEnum(cases, val) { | |
| 78 | + if (cases.indexOf(val) !== -1) return val; | |
| 79 | + return invalidValue(cases.map(a => { return l(a); }), val, key, parent); | |
| 80 | + } | |
| 81 | + | |
| 82 | + function transformArray(typ, val) { | |
| 83 | + // val must be an array with no invalid elements | |
| 84 | + if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent); | |
| 85 | + return val.map(el => transform(el, typ, getProps)); | |
| 86 | + } | |
| 87 | + | |
| 88 | + function transformDate(val) { | |
| 89 | + if (val === null) { | |
| 90 | + return null; | |
| 91 | + } | |
| 92 | + const d = new Date(val); | |
| 93 | + if (isNaN(d.valueOf())) { | |
| 94 | + return invalidValue(l("Date"), val, key, parent); | |
| 95 | + } | |
| 96 | + return d; | |
| 97 | + } | |
| 98 | + | |
| 99 | + function transformObject(props, additional, val) { | |
| 100 | + if (val === null || typeof val !== "object" || Array.isArray(val)) { | |
| 101 | + return invalidValue(l(ref || "object"), val, key, parent); | |
| 102 | + } | |
| 103 | + const result = {}; | |
| 104 | + Object.getOwnPropertyNames(props).forEach(key => { | |
| 105 | + const prop = props[key]; | |
| 106 | + const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined; | |
| 107 | + result[prop.key] = transform(v, prop.typ, getProps, key, ref); | |
| 108 | + }); | |
| 109 | + Object.getOwnPropertyNames(val).forEach(key => { | |
| 110 | + if (!Object.prototype.hasOwnProperty.call(props, key)) { | |
| 111 | + result[key] = transform(val[key], additional, getProps, key, ref); | |
| 112 | + } | |
| 113 | + }); | |
| 114 | + return result; | |
| 115 | + } | |
| 116 | + | |
| 117 | + if (typ === "any") return val; | |
| 118 | + if (typ === null) { | |
| 119 | + if (val === null) return val; | |
| 120 | + return invalidValue(typ, val, key, parent); | |
| 121 | + } | |
| 122 | + if (typ === false) return invalidValue(typ, val, key, parent); | |
| 123 | + let ref = undefined; | |
| 124 | + while (typeof typ === "object" && typ.ref !== undefined) { | |
| 125 | + ref = typ.ref; | |
| 126 | + typ = typeMap[typ.ref]; | |
| 127 | + } | |
| 128 | + if (Array.isArray(typ)) return transformEnum(typ, val); | |
| 129 | + if (typeof typ === "object") { | |
| 130 | + return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val) | |
| 131 | + : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val) | |
| 132 | + : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val) | |
| 133 | + : invalidValue(typ, val, key, parent); | |
| 134 | + } | |
| 135 | + // Numbers can be parsed by Date but shouldn't be. | |
| 136 | + if (typ === Date && typeof val !== "number") return transformDate(val); | |
| 137 | + return transformPrimitive(typ, val); | |
| 138 | +} | |
| 139 | + | |
| 140 | +function cast(val, typ) { | |
| 141 | + return transform(val, typ, jsonToJSProps); | |
| 142 | +} | |
| 143 | + | |
| 144 | +function uncast(val, typ) { | |
| 145 | + return transform(val, typ, jsToJSONProps); | |
| 146 | +} | |
| 147 | + | |
| 148 | +function l(typ) { | |
| 149 | + return { literal: typ }; | |
| 150 | +} | |
| 151 | + | |
| 152 | +function a(typ) { | |
| 153 | + return { arrayItems: typ }; | |
| 154 | +} | |
| 155 | + | |
| 156 | +function u(...typs) { | |
| 157 | + return { unionMembers: typs }; | |
| 158 | +} | |
| 159 | + | |
| 160 | +function o(props, additional) { | |
| 161 | + return { props, additional }; | |
| 162 | +} | |
| 163 | + | |
| 164 | +function m(additional) { | |
| 165 | + const props = []; | |
| 166 | + return { props, additional }; | |
| 167 | +} | |
| 168 | + | |
| 169 | +function r(name) { | |
| 170 | + return { ref: name }; | |
| 171 | +} | |
| 172 | + | |
| 173 | +const typeMap = { | |
| 174 | +}; | |
| 175 | + | |
| 176 | +module.exports = { | |
| 177 | + "topLevelToJson": topLevelToJson, | |
| 178 | + "toTopLevel": toTopLevel, | |
| 179 | +}; |
Aschema-kotlin-jacksondefault / TopLevel.kt+27 −0
| @@ -0,0 +1,27 @@ | ||
| 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 | +val mapper = jacksonObjectMapper().apply { | |
| 17 | + propertyNamingStrategy = PropertyNamingStrategy.LOWER_CAMEL_CASE | |
| 18 | + setSerializationInclusion(JsonInclude.Include.NON_NULL) | |
| 19 | +} | |
| 20 | + | |
| 21 | +class TopLevel(elements: Map<String, Any?>) : HashMap<String, Any?>(elements) { | |
| 22 | + fun toJson() = mapper.writeValueAsString(this) | |
| 23 | + | |
| 24 | + companion object { | |
| 25 | + fun fromJson(json: String) = mapper.readValue<TopLevel>(json) | |
| 26 | + } | |
| 27 | +} |
Aschema-kotlindefault / TopLevel.kt+19 −0
| @@ -0,0 +1,19 @@ | ||
| 1 | +// To parse the JSON, install Klaxon and do: | |
| 2 | +// | |
| 3 | +// val topLevel = TopLevel.fromJson(jsonString) | |
| 4 | + | |
| 5 | +package quicktype | |
| 6 | + | |
| 7 | +import com.beust.klaxon.* | |
| 8 | + | |
| 9 | +private val klaxon = Klaxon() | |
| 10 | + | |
| 11 | +class TopLevel(elements: Map<String, Any?>) : HashMap<String, Any?>(elements) { | |
| 12 | + public fun toJson() = klaxon.toJsonString(this) | |
| 13 | + | |
| 14 | + companion object { | |
| 15 | + public fun fromJson(json: String) = TopLevel ( | |
| 16 | + klaxon.parseJsonObject(java.io.StringReader(json)) as Map<String, Any?> | |
| 17 | + ) | |
| 18 | + } | |
| 19 | +} |
Aschema-kotlinxdefault / TopLevel.kt+13 −0
| @@ -0,0 +1,13 @@ | ||
| 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 | +typealias TopLevel = HashMap<String, JsonElement?> |
Aschema-pikedefault / TopLevel.pmod+23 −0
| @@ -0,0 +1,23 @@ | ||
| 1 | +// This source has been automatically generated by quicktype. | |
| 2 | +// ( https://github.com/quicktype/quicktype ) | |
| 3 | +// | |
| 4 | +// To use this code, simply import it into your project as a Pike module. | |
| 5 | +// To JSON-encode your object, you can pass it to `Standards.JSON.encode` | |
| 6 | +// or call `encode_json` on it. | |
| 7 | +// | |
| 8 | +// To decode a JSON string, first pass it to `Standards.JSON.decode`, | |
| 9 | +// and then pass the result to `<YourClass>_from_JSON`. | |
| 10 | +// It will return an instance of <YourClass>. | |
| 11 | +// Bear in mind that these functions have unexpected behavior, | |
| 12 | +// and will likely throw an error, if the JSON string does not | |
| 13 | +// match the expected interface, even if the JSON itself is valid. | |
| 14 | + | |
| 15 | +typedef mapping(string:mixed) TopLevel; | |
| 16 | + | |
| 17 | +TopLevel TopLevel_from_JSON(mixed json) { | |
| 18 | + mapping(string:mixed) retval = ([]); | |
| 19 | + foreach (json; string k; mixed v) { | |
| 20 | + retval[k] = (mixed) v; | |
| 21 | + } | |
| 22 | + return retval; | |
| 23 | +} |
Aschema-pythondefault / quicktype.py+17 −0
| @@ -0,0 +1,17 @@ | ||
| 1 | +from typing import Any, TypeVar, Callable | |
| 2 | + | |
| 3 | + | |
| 4 | +T = TypeVar("T") | |
| 5 | + | |
| 6 | + | |
| 7 | +def from_dict(f: Callable[[Any], T], x: Any) -> dict[str, T]: | |
| 8 | + assert isinstance(x, dict) | |
| 9 | + return { k: f(v) for (k, v) in x.items() } | |
| 10 | + | |
| 11 | + | |
| 12 | +def top_level_from_dict(s: Any) -> dict[str, Any]: | |
| 13 | + return from_dict(lambda x: x, s) | |
| 14 | + | |
| 15 | + | |
| 16 | +def top_level_to_dict(x: dict[str, Any]) -> Any: | |
| 17 | + return from_dict(lambda x: x, x) |
Aschema-rubydefault / TopLevel.rb+25 −0
| @@ -0,0 +1,25 @@ | ||
| 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["…"] | |
| 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 | +end | |
| 20 | + | |
| 21 | +class TopLevel | |
| 22 | + def self.from_json!(json) | |
| 23 | + Types::Hash[JSON.parse(json, quirks_mode: true)].map { |k, v| [k, Types::Any[v]] }.to_h | |
| 24 | + end | |
| 25 | +end |
Aschema-rustdefault / module_under_test.rs+17 −0
| @@ -0,0 +1,17 @@ | ||
| 1 | +// Example code that deserializes and serializes the model. | |
| 2 | +// extern crate serde; | |
| 3 | +// #[macro_use] | |
| 4 | +// extern crate serde_derive; | |
| 5 | +// extern crate serde_json; | |
| 6 | +// | |
| 7 | +// use generated_module::TopLevel; | |
| 8 | +// | |
| 9 | +// fn main() { | |
| 10 | +// let json = r#"{"answer": 42}"#; | |
| 11 | +// let model: TopLevel = serde_json::from_str(&json).unwrap(); | |
| 12 | +// } | |
| 13 | + | |
| 14 | +use serde::{Serialize, Deserialize}; | |
| 15 | +use std::collections::HashMap; | |
| 16 | + | |
| 17 | +pub type TopLevel = HashMap<String, Option<serde_json::Value>>; |
Aschema-scala3-upickledefault / TopLevel.scala+68 −0
| @@ -0,0 +1,68 @@ | ||
| 1 | +package quicktype | |
| 2 | + | |
| 3 | +// Custom pickler so that missing keys and JSON nulls both read as None, | |
| 4 | +// and None is left out when writing (upickle's default for Option is a | |
| 5 | +// JSON array). | |
| 6 | +object OptionPickler extends upickle.AttributeTagged: | |
| 7 | + import upickle.default.Writer | |
| 8 | + import upickle.default.Reader | |
| 9 | + override implicit def OptionWriter[T: Writer]: Writer[Option[T]] = | |
| 10 | + implicitly[Writer[T]].comap[Option[T]] { | |
| 11 | + case None => null.asInstanceOf[T] | |
| 12 | + case Some(x) => x | |
| 13 | + } | |
| 14 | + | |
| 15 | + override implicit def OptionReader[T: Reader]: Reader[Option[T]] = { | |
| 16 | + new Reader.Delegate[Any, Option[T]](implicitly[Reader[T]].map(Some(_))){ | |
| 17 | + override def visitNull(index: Int) = None | |
| 18 | + } | |
| 19 | + } | |
| 20 | +end OptionPickler | |
| 21 | + | |
| 22 | +// If a union has a null in, then we'll need this too... | |
| 23 | +type NullValue = None.type | |
| 24 | +given OptionPickler.ReadWriter[NullValue] = OptionPickler.readwriter[ujson.Value].bimap[NullValue]( | |
| 25 | + _ => ujson.Null, | |
| 26 | + json => if json.isNull then None else throw new upickle.core.Abort("not null") | |
| 27 | +) | |
| 28 | + | |
| 29 | +object JsonExt: | |
| 30 | + val valueReader = OptionPickler.readwriter[ujson.Value] | |
| 31 | + | |
| 32 | + // upickle's built-in primitive readers are lenient -- the numeric and | |
| 33 | + // boolean readers accept strings, and the string reader accepts | |
| 34 | + // numbers and booleans -- so untagged unions need strict readers to | |
| 35 | + // pick the right member. | |
| 36 | + val strictString: OptionPickler.Reader[String] = valueReader.map { | |
| 37 | + case ujson.Str(s) => s | |
| 38 | + case json => throw new upickle.core.Abort("expected string, got " + json) | |
| 39 | + } | |
| 40 | + val strictLong: OptionPickler.Reader[Long] = valueReader.map { | |
| 41 | + case ujson.Num(n) if n.isWhole => n.toLong | |
| 42 | + case json => throw new upickle.core.Abort("expected integer, got " + json) | |
| 43 | + } | |
| 44 | + val strictDouble: OptionPickler.Reader[Double] = valueReader.map { | |
| 45 | + case ujson.Num(n) => n | |
| 46 | + case json => throw new upickle.core.Abort("expected number, got " + json) | |
| 47 | + } | |
| 48 | + val strictBoolean: OptionPickler.Reader[Boolean] = valueReader.map { | |
| 49 | + case ujson.Bool(b) => b | |
| 50 | + case json => throw new upickle.core.Abort("expected boolean, got " + json) | |
| 51 | + } | |
| 52 | + | |
| 53 | + def badMerge[T](r1: => OptionPickler.Reader[?], rest: OptionPickler.Reader[?]*): OptionPickler.Reader[T] = valueReader.map { json => | |
| 54 | + var t: T | Null = null | |
| 55 | + val stack = Vector.newBuilder[Throwable] | |
| 56 | + (r1 +: rest).foreach { reader => | |
| 57 | + if t == null then | |
| 58 | + try | |
| 59 | + t = OptionPickler.read[T](json, trace = true)(using reader.asInstanceOf[OptionPickler.Reader[T]]) | |
| 60 | + catch | |
| 61 | + case exc => stack += exc | |
| 62 | + } | |
| 63 | + if t != null then t.nn else throw new Exception(json.toString(), stack.result().headOption.getOrElse(null)) | |
| 64 | + } | |
| 65 | +end JsonExt | |
| 66 | + | |
| 67 | + | |
| 68 | +type TopLevel = Map[String, Option[ujson.Value]] |
Aschema-scala3default / TopLevel.scala+12 −0
| @@ -0,0 +1,12 @@ | ||
| 1 | +package quicktype | |
| 2 | + | |
| 3 | +import io.circe.syntax._ | |
| 4 | +import io.circe._ | |
| 5 | +import cats.syntax.functor._ | |
| 6 | + | |
| 7 | +// If a union has a null in, then we'll need this too... | |
| 8 | +type NullValue = None.type | |
| 9 | + | |
| 10 | +type TopLevel = Map[String, Option[Json]] | |
| 11 | + | |
| 12 | +given (using ev : Option[Json]): Encoder[Map[String, Option[Json]]] = Encoder.encodeMap[String, Option[Json]] |
Aschema-schemadefault / TopLevel.schema+6 −0
| @@ -0,0 +1,6 @@ | ||
| 1 | +{ | |
| 2 | + "$schema": "http://json-schema.org/draft-06/schema#", | |
| 3 | + "type": "object", | |
| 4 | + "additionalProperties": {}, | |
| 5 | + "definitions": {} | |
| 6 | +} |
Aschema-swiftdefault / quicktype.swift+310 −0
| @@ -0,0 +1,310 @@ | ||
| 1 | +// This file was generated from JSON Schema using quicktype, do not modify it directly. | |
| 2 | +// To parse the JSON, add this file to your project and do: | |
| 3 | +// | |
| 4 | +// let topLevel = try TopLevel(json) | |
| 5 | +import Foundation | |
| 6 | + | |
| 7 | +typealias TopLevel = [String: JSONAny] | |
| 8 | + | |
| 9 | +extension Dictionary where Key == String, Value == JSONAny { | |
| 10 | + init(data: Data) throws { | |
| 11 | + self = try newJSONDecoder().decode(TopLevel.self, from: data) | |
| 12 | + } | |
| 13 | + | |
| 14 | + init(_ json: String, using encoding: String.Encoding = .utf8) throws { | |
| 15 | + guard let data = json.data(using: encoding) else { | |
| 16 | + throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) | |
| 17 | + } | |
| 18 | + try self.init(data: data) | |
| 19 | + } | |
| 20 | + | |
| 21 | + init(fromURL url: URL) throws { | |
| 22 | + try self.init(data: try Data(contentsOf: url)) | |
| 23 | + } | |
| 24 | + | |
| 25 | + func jsonData() throws -> Data { | |
| 26 | + return try newJSONEncoder().encode(self) | |
| 27 | + } | |
| 28 | + | |
| 29 | + func jsonString(encoding: String.Encoding = .utf8) throws -> String? { | |
| 30 | + return String(data: try self.jsonData(), encoding: encoding) | |
| 31 | + } | |
| 32 | +} | |
| 33 | + | |
| 34 | +// MARK: - Helper functions for creating encoders and decoders | |
| 35 | + | |
| 36 | +func newJSONDecoder() -> JSONDecoder { | |
| 37 | + let decoder = JSONDecoder() | |
| 38 | + decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in | |
| 39 | + let container = try decoder.singleValueContainer() | |
| 40 | + let dateStr = try container.decode(String.self) | |
| 41 | + | |
| 42 | + let formatter = DateFormatter() | |
| 43 | + formatter.calendar = Calendar(identifier: .iso8601) | |
| 44 | + formatter.locale = Locale(identifier: "en_US_POSIX") | |
| 45 | + formatter.timeZone = TimeZone(secondsFromGMT: 0) | |
| 46 | + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX" | |
| 47 | + if let date = formatter.date(from: dateStr) { | |
| 48 | + return date | |
| 49 | + } | |
| 50 | + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX" | |
| 51 | + if let date = formatter.date(from: dateStr) { | |
| 52 | + return date | |
| 53 | + } | |
| 54 | + throw DecodingError.typeMismatch(Date.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not decode date")) | |
| 55 | + }) | |
| 56 | + return decoder | |
| 57 | +} | |
| 58 | + | |
| 59 | +func newJSONEncoder() -> JSONEncoder { | |
| 60 | + let encoder = JSONEncoder() | |
| 61 | + let formatter = DateFormatter() | |
| 62 | + formatter.calendar = Calendar(identifier: .iso8601) | |
| 63 | + formatter.locale = Locale(identifier: "en_US_POSIX") | |
| 64 | + formatter.timeZone = TimeZone(secondsFromGMT: 0) | |
| 65 | + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX" | |
| 66 | + encoder.dateEncodingStrategy = .formatted(formatter) | |
| 67 | + return encoder | |
| 68 | +} | |
| 69 | + | |
| 70 | +// MARK: - Encode/decode helpers | |
| 71 | + | |
| 72 | +class JSONNull: Codable, Hashable { | |
| 73 | + | |
| 74 | + public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool { | |
| 75 | + return true | |
| 76 | + } | |
| 77 | + | |
| 78 | + public func hash(into hasher: inout Hasher) { | |
| 79 | + hasher.combine(0) | |
| 80 | + } | |
| 81 | + | |
| 82 | + public init() {} | |
| 83 | + | |
| 84 | + public required init(from decoder: Decoder) throws { | |
| 85 | + let container = try decoder.singleValueContainer() | |
| 86 | + if !container.decodeNil() { | |
| 87 | + throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull")) | |
| 88 | + } | |
| 89 | + } | |
| 90 | + | |
| 91 | + public func encode(to encoder: Encoder) throws { | |
| 92 | + var container = encoder.singleValueContainer() | |
| 93 | + try container.encodeNil() | |
| 94 | + } | |
| 95 | +} | |
| 96 | + | |
| 97 | +class JSONCodingKey: CodingKey { | |
| 98 | + let key: String | |
| 99 | + | |
| 100 | + required init?(intValue: Int) { | |
| 101 | + return nil | |
| 102 | + } | |
| 103 | + | |
| 104 | + required init?(stringValue: String) { | |
| 105 | + key = stringValue | |
| 106 | + } | |
| 107 | + | |
| 108 | + var intValue: Int? { | |
| 109 | + return nil | |
| 110 | + } | |
| 111 | + | |
| 112 | + var stringValue: String { | |
| 113 | + return key | |
| 114 | + } | |
| 115 | +} | |
| 116 | + | |
| 117 | +class JSONAny: Codable { | |
| 118 | + | |
| 119 | + let value: Any | |
| 120 | + | |
| 121 | + static func decodingError(forCodingPath codingPath: [CodingKey]) -> DecodingError { | |
| 122 | + let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Cannot decode JSONAny") | |
| 123 | + return DecodingError.typeMismatch(JSONAny.self, context) | |
| 124 | + } | |
| 125 | + | |
| 126 | + static func encodingError(forValue value: Any, codingPath: [CodingKey]) -> EncodingError { | |
| 127 | + let context = EncodingError.Context(codingPath: codingPath, debugDescription: "Cannot encode JSONAny") | |
| 128 | + return EncodingError.invalidValue(value, context) | |
| 129 | + } | |
| 130 | + | |
| 131 | + static func decode(from container: SingleValueDecodingContainer) throws -> Any { | |
| 132 | + if let value = try? container.decode(Bool.self) { | |
| 133 | + return value | |
| 134 | + } | |
| 135 | + if let value = try? container.decode(Int64.self) { | |
| 136 | + return value | |
| 137 | + } | |
| 138 | + if let value = try? container.decode(Double.self) { | |
| 139 | + return value | |
| 140 | + } | |
| 141 | + if let value = try? container.decode(String.self) { | |
| 142 | + return value | |
| 143 | + } | |
| 144 | + if container.decodeNil() { | |
| 145 | + return JSONNull() | |
| 146 | + } | |
| 147 | + throw decodingError(forCodingPath: container.codingPath) | |
| 148 | + } | |
| 149 | + | |
| 150 | + static func decode(from container: inout UnkeyedDecodingContainer) throws -> Any { | |
| 151 | + if let value = try? container.decode(Bool.self) { | |
| 152 | + return value | |
| 153 | + } | |
| 154 | + if let value = try? container.decode(Int64.self) { | |
| 155 | + return value | |
| 156 | + } | |
| 157 | + if let value = try? container.decode(Double.self) { | |
| 158 | + return value | |
| 159 | + } | |
| 160 | + if let value = try? container.decode(String.self) { | |
| 161 | + return value | |
| 162 | + } | |
| 163 | + if let value = try? container.decodeNil() { | |
| 164 | + if value { | |
| 165 | + return JSONNull() | |
| 166 | + } | |
| 167 | + } | |
| 168 | + if var container = try? container.nestedUnkeyedContainer() { | |
| 169 | + return try decodeArray(from: &container) | |
| 170 | + } | |
| 171 | + if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self) { | |
| 172 | + return try decodeDictionary(from: &container) | |
| 173 | + } | |
| 174 | + throw decodingError(forCodingPath: container.codingPath) | |
| 175 | + } | |
| 176 | + | |
| 177 | + static func decode(from container: inout KeyedDecodingContainer<JSONCodingKey>, forKey key: JSONCodingKey) throws -> Any { | |
| 178 | + if let value = try? container.decode(Bool.self, forKey: key) { | |
| 179 | + return value | |
| 180 | + } | |
| 181 | + if let value = try? container.decode(Int64.self, forKey: key) { | |
| 182 | + return value | |
| 183 | + } | |
| 184 | + if let value = try? container.decode(Double.self, forKey: key) { | |
| 185 | + return value | |
| 186 | + } | |
| 187 | + if let value = try? container.decode(String.self, forKey: key) { | |
| 188 | + return value | |
| 189 | + } | |
| 190 | + if let value = try? container.decodeNil(forKey: key) { | |
| 191 | + if value { | |
| 192 | + return JSONNull() | |
| 193 | + } | |
| 194 | + } | |
| 195 | + if var container = try? container.nestedUnkeyedContainer(forKey: key) { | |
| 196 | + return try decodeArray(from: &container) | |
| 197 | + } | |
| 198 | + if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key) { | |
| 199 | + return try decodeDictionary(from: &container) | |
| 200 | + } | |
| 201 | + throw decodingError(forCodingPath: container.codingPath) | |
| 202 | + } | |
| 203 | + | |
| 204 | + static func decodeArray(from container: inout UnkeyedDecodingContainer) throws -> [Any] { | |
| 205 | + var arr: [Any] = [] | |
| 206 | + while !container.isAtEnd { | |
| 207 | + let value = try decode(from: &container) | |
| 208 | + arr.append(value) | |
| 209 | + } | |
| 210 | + return arr | |
| 211 | + } | |
| 212 | + | |
| 213 | + static func decodeDictionary(from container: inout KeyedDecodingContainer<JSONCodingKey>) throws -> [String: Any] { | |
| 214 | + var dict = [String: Any]() | |
| 215 | + for key in container.allKeys { | |
| 216 | + let value = try decode(from: &container, forKey: key) | |
| 217 | + dict[key.stringValue] = value | |
| 218 | + } | |
| 219 | + return dict | |
| 220 | + } | |
| 221 | + | |
| 222 | + static func encode(to container: inout UnkeyedEncodingContainer, array: [Any]) throws { | |
| 223 | + for value in array { | |
| 224 | + if let value = value as? Bool { | |
| 225 | + try container.encode(value) | |
| 226 | + } else if let value = value as? Int64 { | |
| 227 | + try container.encode(value) | |
| 228 | + } else if let value = value as? Double { | |
| 229 | + try container.encode(value) | |
| 230 | + } else if let value = value as? String { | |
| 231 | + try container.encode(value) | |
| 232 | + } else if value is JSONNull { | |
| 233 | + try container.encodeNil() | |
| 234 | + } else if let value = value as? [Any] { | |
| 235 | + var container = container.nestedUnkeyedContainer() | |
| 236 | + try encode(to: &container, array: value) | |
| 237 | + } else if let value = value as? [String: Any] { | |
| 238 | + var container = container.nestedContainer(keyedBy: JSONCodingKey.self) | |
| 239 | + try encode(to: &container, dictionary: value) | |
| 240 | + } else { | |
| 241 | + throw encodingError(forValue: value, codingPath: container.codingPath) | |
| 242 | + } | |
| 243 | + } | |
| 244 | + } | |
| 245 | + | |
| 246 | + static func encode(to container: inout KeyedEncodingContainer<JSONCodingKey>, dictionary: [String: Any]) throws { | |
| 247 | + for (key, value) in dictionary { | |
| 248 | + let key = JSONCodingKey(stringValue: key)! | |
| 249 | + if let value = value as? Bool { | |
| 250 | + try container.encode(value, forKey: key) | |
| 251 | + } else if let value = value as? Int64 { | |
| 252 | + try container.encode(value, forKey: key) | |
| 253 | + } else if let value = value as? Double { | |
| 254 | + try container.encode(value, forKey: key) | |
| 255 | + } else if let value = value as? String { | |
| 256 | + try container.encode(value, forKey: key) | |
| 257 | + } else if value is JSONNull { | |
| 258 | + try container.encodeNil(forKey: key) | |
| 259 | + } else if let value = value as? [Any] { | |
| 260 | + var container = container.nestedUnkeyedContainer(forKey: key) | |
| 261 | + try encode(to: &container, array: value) | |
| 262 | + } else if let value = value as? [String: Any] { | |
| 263 | + var container = container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key) | |
| 264 | + try encode(to: &container, dictionary: value) | |
| 265 | + } else { | |
| 266 | + throw encodingError(forValue: value, codingPath: container.codingPath) | |
| 267 | + } | |
| 268 | + } | |
| 269 | + } | |
| 270 | + | |
| 271 | + static func encode(to container: inout SingleValueEncodingContainer, value: Any) throws { | |
| 272 | + if let value = value as? Bool { | |
| 273 | + try container.encode(value) | |
| 274 | + } else if let value = value as? Int64 { | |
| 275 | + try container.encode(value) | |
| 276 | + } else if let value = value as? Double { | |
| 277 | + try container.encode(value) | |
| 278 | + } else if let value = value as? String { | |
| 279 | + try container.encode(value) | |
| 280 | + } else if value is JSONNull { | |
| 281 | + try container.encodeNil() | |
| 282 | + } else { | |
| 283 | + throw encodingError(forValue: value, codingPath: container.codingPath) | |
| 284 | + } | |
| 285 | + } | |
| 286 | + | |
| 287 | + public required init(from decoder: Decoder) throws { | |
| 288 | + if var arrayContainer = try? decoder.unkeyedContainer() { | |
| 289 | + self.value = try JSONAny.decodeArray(from: &arrayContainer) | |
| 290 | + } else if var container = try? decoder.container(keyedBy: JSONCodingKey.self) { | |
| 291 | + self.value = try JSONAny.decodeDictionary(from: &container) | |
| 292 | + } else { | |
| 293 | + let container = try decoder.singleValueContainer() | |
| 294 | + self.value = try JSONAny.decode(from: container) | |
| 295 | + } | |
| 296 | + } | |
| 297 | + | |
| 298 | + public func encode(to encoder: Encoder) throws { | |
| 299 | + if let arr = self.value as? [Any] { | |
| 300 | + var container = encoder.unkeyedContainer() | |
| 301 | + try JSONAny.encode(to: &container, array: arr) | |
| 302 | + } else if let dict = self.value as? [String: Any] { | |
| 303 | + var container = encoder.container(keyedBy: JSONCodingKey.self) | |
| 304 | + try JSONAny.encode(to: &container, dictionary: dict) | |
| 305 | + } else { | |
| 306 | + var container = encoder.singleValueContainer() | |
| 307 | + try JSONAny.encode(to: &container, value: self.value) | |
| 308 | + } | |
| 309 | + } | |
| 310 | +} |
Aschema-typescriptdefault / TopLevel.ts+178 −0
| @@ -0,0 +1,178 @@ | ||
| 1 | +// To parse this data: | |
| 2 | +// | |
| 3 | +// import { Convert } from "./TopLevel"; | |
| 4 | +// | |
| 5 | +// const topLevel = Convert.toTopLevel(json); | |
| 6 | +// | |
| 7 | +// These functions will throw an error if the JSON doesn't | |
| 8 | +// match the expected interface, even if the JSON is valid. | |
| 9 | + | |
| 10 | +export type TopLevel = { [key: string]: unknown }; | |
| 11 | + | |
| 12 | +// Converts JSON strings to/from your types | |
| 13 | +// and asserts the results of JSON.parse at runtime | |
| 14 | +export class Convert { | |
| 15 | + public static toTopLevel(json: string): { [key: string]: unknown } { | |
| 16 | + return cast(JSON.parse(json), m("any")); | |
| 17 | + } | |
| 18 | + | |
| 19 | + public static topLevelToJson(value: { [key: string]: unknown }): string { | |
| 20 | + return JSON.stringify(uncast(value, m("any")), null, 2); | |
| 21 | + } | |
| 22 | +} | |
| 23 | + | |
| 24 | +function invalidValue(typ: any, val: any, key: any, parent: any = ''): never { | |
| 25 | + const prettyTyp = prettyTypeName(typ); | |
| 26 | + const parentText = parent ? ` on ${parent}` : ''; | |
| 27 | + const keyText = key ? ` for key "${key}"` : ''; | |
| 28 | + throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`); | |
| 29 | +} | |
| 30 | + | |
| 31 | +function prettyTypeName(typ: any): string { | |
| 32 | + if (Array.isArray(typ)) { | |
| 33 | + if (typ.length === 2 && typ[0] === undefined) { | |
| 34 | + return `an optional ${prettyTypeName(typ[1])}`; | |
| 35 | + } else { | |
| 36 | + return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`; | |
| 37 | + } | |
| 38 | + } else if (typeof typ === "object" && typ.literal !== undefined) { | |
| 39 | + return typ.literal; | |
| 40 | + } else { | |
| 41 | + return typeof typ; | |
| 42 | + } | |
| 43 | +} | |
| 44 | + | |
| 45 | +function jsonToJSProps(typ: any): any { | |
| 46 | + if (typ.jsonToJS === undefined) { | |
| 47 | + const map: any = {}; | |
| 48 | + typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ }); | |
| 49 | + typ.jsonToJS = map; | |
| 50 | + } | |
| 51 | + return typ.jsonToJS; | |
| 52 | +} | |
| 53 | + | |
| 54 | +function jsToJSONProps(typ: any): any { | |
| 55 | + if (typ.jsToJSON === undefined) { | |
| 56 | + const map: any = {}; | |
| 57 | + typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ }); | |
| 58 | + typ.jsToJSON = map; | |
| 59 | + } | |
| 60 | + return typ.jsToJSON; | |
| 61 | +} | |
| 62 | + | |
| 63 | +function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any { | |
| 64 | + function transformPrimitive(typ: string, val: any): any { | |
| 65 | + if (typeof typ === typeof val) return val; | |
| 66 | + return invalidValue(typ, val, key, parent); | |
| 67 | + } | |
| 68 | + | |
| 69 | + function transformUnion(typs: any[], val: any): any { | |
| 70 | + // val must validate against one typ in typs | |
| 71 | + const l = typs.length; | |
| 72 | + for (let i = 0; i < l; i++) { | |
| 73 | + const typ = typs[i]; | |
| 74 | + try { | |
| 75 | + return transform(val, typ, getProps); | |
| 76 | + } catch (_) {} | |
| 77 | + } | |
| 78 | + return invalidValue(typs, val, key, parent); | |
| 79 | + } | |
| 80 | + | |
| 81 | + function transformEnum(cases: string[], val: any): any { | |
| 82 | + if (cases.indexOf(val) !== -1) return val; | |
| 83 | + return invalidValue(cases.map(a => { return l(a); }), val, key, parent); | |
| 84 | + } | |
| 85 | + | |
| 86 | + function transformArray(typ: any, val: any): any { | |
| 87 | + // val must be an array with no invalid elements | |
| 88 | + if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent); | |
| 89 | + return val.map(el => transform(el, typ, getProps)); | |
| 90 | + } | |
| 91 | + | |
| 92 | + function transformDate(val: any): any { | |
| 93 | + if (val === null) { | |
| 94 | + return null; | |
| 95 | + } | |
| 96 | + const d = new Date(val); | |
| 97 | + if (isNaN(d.valueOf())) { | |
| 98 | + return invalidValue(l("Date"), val, key, parent); | |
| 99 | + } | |
| 100 | + return d; | |
| 101 | + } | |
| 102 | + | |
| 103 | + function transformObject(props: { [k: string]: any }, additional: any, val: any): any { | |
| 104 | + if (val === null || typeof val !== "object" || Array.isArray(val)) { | |
| 105 | + return invalidValue(l(ref || "object"), val, key, parent); | |
| 106 | + } | |
| 107 | + const result: any = {}; | |
| 108 | + Object.getOwnPropertyNames(props).forEach(key => { | |
| 109 | + const prop = props[key]; | |
| 110 | + const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined; | |
| 111 | + result[prop.key] = transform(v, prop.typ, getProps, key, ref); | |
| 112 | + }); | |
| 113 | + Object.getOwnPropertyNames(val).forEach(key => { | |
| 114 | + if (!Object.prototype.hasOwnProperty.call(props, key)) { | |
| 115 | + result[key] = transform(val[key], additional, getProps, key, ref); | |
| 116 | + } | |
| 117 | + }); | |
| 118 | + return result; | |
| 119 | + } | |
| 120 | + | |
| 121 | + if (typ === "any") return val; | |
| 122 | + if (typ === null) { | |
| 123 | + if (val === null) return val; | |
| 124 | + return invalidValue(typ, val, key, parent); | |
| 125 | + } | |
| 126 | + if (typ === false) return invalidValue(typ, val, key, parent); | |
| 127 | + let ref: any = undefined; | |
| 128 | + while (typeof typ === "object" && typ.ref !== undefined) { | |
| 129 | + ref = typ.ref; | |
| 130 | + typ = typeMap[typ.ref]; | |
| 131 | + } | |
| 132 | + if (Array.isArray(typ)) return transformEnum(typ, val); | |
| 133 | + if (typeof typ === "object") { | |
| 134 | + return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val) | |
| 135 | + : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val) | |
| 136 | + : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val) | |
| 137 | + : invalidValue(typ, val, key, parent); | |
| 138 | + } | |
| 139 | + // Numbers can be parsed by Date but shouldn't be. | |
| 140 | + if (typ === Date && typeof val !== "number") return transformDate(val); | |
| 141 | + return transformPrimitive(typ, val); | |
| 142 | +} | |
| 143 | + | |
| 144 | +function cast<T>(val: any, typ: any): T { | |
| 145 | + return transform(val, typ, jsonToJSProps); | |
| 146 | +} | |
| 147 | + | |
| 148 | +function uncast<T>(val: T, typ: any): any { | |
| 149 | + return transform(val, typ, jsToJSONProps); | |
| 150 | +} | |
| 151 | + | |
| 152 | +function l(typ: any) { | |
| 153 | + return { literal: typ }; | |
| 154 | +} | |
| 155 | + | |
| 156 | +function a(typ: any) { | |
| 157 | + return { arrayItems: typ }; | |
| 158 | +} | |
| 159 | + | |
| 160 | +function u(...typs: any[]) { | |
| 161 | + return { unionMembers: typs }; | |
| 162 | +} | |
| 163 | + | |
| 164 | +function o(props: any[], additional: any) { | |
| 165 | + return { props, additional }; | |
| 166 | +} | |
| 167 | + | |
| 168 | +function m(additional: any) { | |
| 169 | + const props: any[] = []; | |
| 170 | + return { props, additional }; | |
| 171 | +} | |
| 172 | + | |
| 173 | +function r(name: string) { | |
| 174 | + return { ref: name }; | |
| 175 | +} | |
| 176 | + | |
| 177 | +const typeMap: any = { | |
| 178 | +}; |
Test case
2 generated files · +4 −0test/inputs/schema/issue2680-top-level-array.schema
Mschema-flowdefault / TopLevel.js+2 −0
| @@ -9,6 +9,8 @@ | ||
| 9 | 9 | // These functions will throw an error if the JSON doesn't |
| 10 | 10 | // match the expected interface, even if the JSON is valid. |
| 11 | 11 | |
| 12 | +export type TopLevel = number[]; | |
| 13 | + | |
| 12 | 14 | // Converts JSON strings to/from your types |
| 13 | 15 | // and asserts the results of JSON.parse at runtime |
| 14 | 16 | function toTopLevel(json: string): number[] { |
Mschema-typescriptdefault / TopLevel.ts+2 −0
| @@ -7,6 +7,8 @@ | ||
| 7 | 7 | // These functions will throw an error if the JSON doesn't |
| 8 | 8 | // match the expected interface, even if the JSON is valid. |
| 9 | 9 | |
| 10 | +export type TopLevel = number[]; | |
| 11 | + | |
| 10 | 12 | // Converts JSON strings to/from your types |
| 11 | 13 | // and asserts the results of JSON.parse at runtime |
| 12 | 14 | export class Convert { |
Test case
2 generated files · +2 −2test/inputs/schema/top-level-primitive.schema
Mschema-flowdefault / TopLevel.js+1 −1
| @@ -12,7 +12,7 @@ | ||
| 12 | 12 | /** |
| 13 | 13 | * Top level primitive |
| 14 | 14 | */ |
| 15 | -type TopLevel = number; | |
| 15 | +export type TopLevel = number; | |
| 16 | 16 | |
| 17 | 17 | // Converts JSON strings to/from your types |
| 18 | 18 | // and asserts the results of JSON.parse at runtime |
Mschema-typescriptdefault / TopLevel.ts+1 −1
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | /** |
| 11 | 11 | * Top level primitive |
| 12 | 12 | */ |
| 13 | -type TopLevel = number; | |
| 13 | +export type TopLevel = number; | |
| 14 | 14 | |
| 15 | 15 | // Converts JSON strings to/from your types |
| 16 | 16 | // and asserts the results of JSON.parse at runtime |
No generated files match these filters.