Generated-output differences

quicktype output changed between the PR base and tested PR merge revisions.
← Back to the pull request
1test cases
37files differ
0modified
37new
0deleted
2,822changed lines
+2,822 −0insertions / deletions
Base 66df8a7480383ad7d4784464b395df83fd482c7f · PR merge 5706977810a691ca7ee3584758f17623b1bdd834 · Head 82c877d3e3221cd725c782021b45f45d2f85087f · raw patch
Test case

test/inputs/json/samples/dart-object-members.json

37 generated files · +2,822 −0
Acjsondefault / TopLevel.c+105 −0
@@ -0,0 +1,105 @@
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+ if (!cJSON_HasObjectItem(j, "hashCode")) { cJSON_DeleteTopLevel(x); return NULL; }
26+ if (cJSON_HasObjectItem(j, "hashCode")) {
27+ if (!cJSON_IsString(cJSON_GetObjectItemCaseSensitive(j, "hashCode"))) { cJSON_DeleteTopLevel(x); return NULL; }
28+ x->hash_code = strdup(cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(j, "hashCode")));
29+ }
30+ else {
31+ if (NULL != (x->hash_code = cJSON_malloc(sizeof(char)))) {
32+ x->hash_code[0] = '\0';
33+ }
34+ }
35+ if (!cJSON_HasObjectItem(j, "noSuchMethod")) { cJSON_DeleteTopLevel(x); return NULL; }
36+ if (cJSON_HasObjectItem(j, "noSuchMethod")) {
37+ if (!cJSON_IsString(cJSON_GetObjectItemCaseSensitive(j, "noSuchMethod"))) { cJSON_DeleteTopLevel(x); return NULL; }
38+ x->no_such_method = strdup(cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(j, "noSuchMethod")));
39+ }
40+ else {
41+ if (NULL != (x->no_such_method = cJSON_malloc(sizeof(char)))) {
42+ x->no_such_method[0] = '\0';
43+ }
44+ }
45+ if (!cJSON_HasObjectItem(j, "runtimeType")) { cJSON_DeleteTopLevel(x); return NULL; }
46+ if (cJSON_HasObjectItem(j, "runtimeType")) {
47+ if (!quicktype_cJSON_IsInteger(cJSON_GetObjectItemCaseSensitive(j, "runtimeType"))) { cJSON_DeleteTopLevel(x); return NULL; }
48+ x->runtime_type = cJSON_GetNumberValue(cJSON_GetObjectItemCaseSensitive(j, "runtimeType"));
49+ }
50+ if (!cJSON_HasObjectItem(j, "toString")) { cJSON_DeleteTopLevel(x); return NULL; }
51+ if (cJSON_HasObjectItem(j, "toString")) {
52+ if (!cJSON_IsBool(cJSON_GetObjectItemCaseSensitive(j, "toString"))) { cJSON_DeleteTopLevel(x); return NULL; }
53+ x->to_string = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(j, "toString"));
54+ }
55+ }
56+ }
57+ return x;
58+}
59+
60+cJSON * cJSON_CreateTopLevel(const struct TopLevel * x) {
61+ cJSON * j = NULL;
62+ if (NULL != x) {
63+ if (NULL != (j = cJSON_CreateObject())) {
64+ if (NULL != x->hash_code) {
65+ cJSON_AddStringToObject(j, "hashCode", x->hash_code);
66+ }
67+ else {
68+ cJSON_AddStringToObject(j, "hashCode", "");
69+ }
70+ if (NULL != x->no_such_method) {
71+ cJSON_AddStringToObject(j, "noSuchMethod", x->no_such_method);
72+ }
73+ else {
74+ cJSON_AddStringToObject(j, "noSuchMethod", "");
75+ }
76+ cJSON_AddNumberToObject(j, "runtimeType", x->runtime_type);
77+ cJSON_AddBoolToObject(j, "toString", x->to_string);
78+ }
79+ }
80+ return j;
81+}
82+
83+char * cJSON_PrintTopLevel(const struct TopLevel * x) {
84+ char * s = NULL;
85+ if (NULL != x) {
86+ cJSON * j = cJSON_CreateTopLevel(x);
87+ if (NULL != j) {
88+ s = cJSON_Print(j);
89+ cJSON_Delete(j);
90+ }
91+ }
92+ return s;
93+}
94+
95+void cJSON_DeleteTopLevel(struct TopLevel * x) {
96+ if (NULL != x) {
97+ if (NULL != x->hash_code) {
98+ cJSON_free(x->hash_code);
99+ }
100+ if (NULL != x->no_such_method) {
101+ cJSON_free(x->no_such_method);
102+ }
103+ cJSON_free(x);
104+ }
105+}
Acjsondefault / TopLevel.h+58 −0
@@ -0,0 +1,58 @@
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 <regex.h>
24+#include <cJSON.h>
25+#include <hashtable.h>
26+#include <list.h>
27+
28+#define quicktype_cJSON_Duplicate(j) cJSON_Duplicate(j, true)
29+#define cJSON_Integer (1 << 18)
30+#define quicktype_cJSON_IsInteger(j) (cJSON_IsNumber(j) && (j)->valuedouble == (int64_t)(j)->valuedouble)
31+#ifndef cJSON_Bool
32+#define cJSON_Bool (cJSON_True | cJSON_False)
33+#endif
34+#ifndef cJSON_Map
35+#define cJSON_Map (1 << 16)
36+#endif
37+#ifndef cJSON_Enum
38+#define cJSON_Enum (1 << 17)
39+#endif
40+
41+struct TopLevel {
42+ char * hash_code;
43+ char * no_such_method;
44+ int64_t runtime_type;
45+ bool to_string;
46+};
47+
48+struct TopLevel * cJSON_ParseTopLevel(const char * s);
49+struct TopLevel * cJSON_GetTopLevelValue(const cJSON * j);
50+cJSON * cJSON_CreateTopLevel(const struct TopLevel * x);
51+char * cJSON_PrintTopLevel(const struct TopLevel * x);
52+void cJSON_DeleteTopLevel(struct TopLevel * x);
53+
54+#ifdef __cplusplus
55+}
56+#endif
57+
58+#endif /* __TOPLEVEL_H__ */
Acplusplusdefault / quicktype.hpp+84 −0
@@ -0,0 +1,84 @@
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+ class TopLevel {
35+ public:
36+ TopLevel() = default;
37+ virtual ~TopLevel() = default;
38+
39+ private:
40+ std::string hash_code;
41+ std::string no_such_method;
42+ int64_t runtime_type;
43+ bool to_string;
44+
45+ public:
46+ const std::string & get_hash_code() const { return hash_code; }
47+ std::string & get_mutable_hash_code() { return hash_code; }
48+ void set_hash_code(const std::string & value) { this->hash_code = value; }
49+
50+ const std::string & get_no_such_method() const { return no_such_method; }
51+ std::string & get_mutable_no_such_method() { return no_such_method; }
52+ void set_no_such_method(const std::string & value) { this->no_such_method = value; }
53+
54+ const int64_t & get_runtime_type() const { return runtime_type; }
55+ int64_t & get_mutable_runtime_type() { return runtime_type; }
56+ void set_runtime_type(const int64_t & value) { this->runtime_type = value; }
57+
58+ const bool & get_to_string() const { return to_string; }
59+ bool & get_mutable_to_string() { return to_string; }
60+ void set_to_string(const bool & value) { this->to_string = value; }
61+ };
62+}
63+
64+namespace quicktype {
65+ void from_json(const json & j, TopLevel & x);
66+ void to_json(json & j, const TopLevel & x);
67+
68+ inline void from_json(const json & j, TopLevel& x) {
69+ if (!j.is_object()) throw std::runtime_error("Expected object");
70+ x.set_hash_code(j.at("hashCode").get<std::string>());
71+ x.set_no_such_method(j.at("noSuchMethod").get<std::string>());
72+ if (j.find("runtimeType") != j.end() && !j.at("runtimeType").is_number_integer()) throw std::runtime_error("Expected integer");
73+ x.set_runtime_type(j.at("runtimeType").get<int64_t>());
74+ x.set_to_string(j.at("toString").get<bool>());
75+ }
76+
77+ inline void to_json(json & j, const TopLevel & x) {
78+ j = json::object();
79+ j["hashCode"] = x.get_hash_code();
80+ j["noSuchMethod"] = x.get_no_such_method();
81+ j["runtimeType"] = x.get_runtime_type();
82+ j["toString"] = x.get_to_string();
83+ }
84+}
Acrystaldefault / TopLevel.cr+17 −0
@@ -0,0 +1,17 @@
1+require "json"
2+
3+class TopLevel
4+ include JSON::Serializable
5+
6+ @[JSON::Field(key: "hashCode")]
7+ property hash_code : String
8+
9+ @[JSON::Field(key: "noSuchMethod")]
10+ property no_such_method : String
11+
12+ @[JSON::Field(key: "runtimeType")]
13+ property runtime_type : Int64
14+
15+ @[JSON::Field(key: "toString")]
16+ property to_string : Bool
17+end
Acsharp-recordsdefault / QuickType.cs+70 −0
@@ -0,0 +1,70 @@
1+// <auto-generated />
2+//
3+// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
4+//
5+// using QuickType;
6+//
7+// var topLevel = TopLevel.FromJson(jsonString);
8+#nullable enable
9+#pragma warning disable CS8618
10+#pragma warning disable CS8601
11+#pragma warning disable CS8602
12+#pragma warning disable CS8603
13+#pragma warning disable CS8604
14+#pragma warning disable CS8625
15+#pragma warning disable CS8765
16+
17+namespace QuickType
18+{
19+ using System;
20+ using System.Collections.Generic;
21+
22+ using System.Globalization;
23+ using Newtonsoft.Json;
24+ using Newtonsoft.Json.Converters;
25+
26+ public partial record TopLevel
27+ {
28+ [JsonProperty("hashCode", Required = Required.Always)]
29+ public string HashCode { get; set; }
30+
31+ [JsonProperty("noSuchMethod", Required = Required.Always)]
32+ public string NoSuchMethod { get; set; }
33+
34+ [JsonProperty("runtimeType", Required = Required.Always)]
35+ public long RuntimeType { get; set; }
36+
37+ [JsonProperty("toString", Required = Required.Always)]
38+ public bool TopLevelToString { get; set; }
39+ }
40+
41+ public partial record TopLevel
42+ {
43+ public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings);
44+ }
45+
46+ public static partial class Serialize
47+ {
48+ public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
49+ }
50+
51+ internal static partial class Converter
52+ {
53+ public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
54+ {
55+ MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
56+ DateParseHandling = DateParseHandling.None,
57+ Converters =
58+ {
59+ new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
60+ },
61+ };
62+ }
63+}
64+#pragma warning restore CS8618
65+#pragma warning restore CS8601
66+#pragma warning restore CS8602
67+#pragma warning restore CS8603
68+#pragma warning restore CS8604
69+#pragma warning restore CS8625
70+#pragma warning restore CS8765
Acsharp-SystemTextJsondefault / QuickType.cs+178 −0
@@ -0,0 +1,178 @@
1+// <auto-generated />
2+//
3+// To parse this JSON data, add NuGet 'System.Text.Json' then do:
4+//
5+// using QuickType;
6+//
7+// var topLevel = TopLevel.FromJson(jsonString);
8+#nullable enable
9+#pragma warning disable CS8618
10+#pragma warning disable CS8601
11+#pragma warning disable CS8602
12+#pragma warning disable CS8603
13+
14+namespace QuickType
15+{
16+ using System;
17+ using System.Collections.Generic;
18+
19+ using System.Text.Json;
20+ using System.Text.Json.Serialization;
21+ using System.Globalization;
22+
23+ public partial class TopLevel
24+ {
25+ [JsonRequired]
26+ [JsonPropertyName("hashCode")]
27+ public string HashCode { get; set; }
28+
29+ [JsonRequired]
30+ [JsonPropertyName("noSuchMethod")]
31+ public string NoSuchMethod { get; set; }
32+
33+ [JsonRequired]
34+ [JsonPropertyName("runtimeType")]
35+ public long RuntimeType { get; set; }
36+
37+ [JsonRequired]
38+ [JsonPropertyName("toString")]
39+ public bool TopLevelToString { get; set; }
40+ }
41+
42+ public partial class TopLevel
43+ {
44+ public static TopLevel FromJson(string json) => global::System.Text.Json.JsonSerializer.Deserialize<TopLevel>(json, QuickType.Converter.Settings);
45+ }
46+
47+ public static partial class Serialize
48+ {
49+ public static string ToJson(this TopLevel self) => JsonSerializer.Serialize(self, QuickType.Converter.Settings);
50+ }
51+
52+ internal static partial class Converter
53+ {
54+ public static readonly JsonSerializerOptions Settings = new(JsonSerializerDefaults.General)
55+ {
56+ Converters =
57+ {
58+ new DateOnlyConverter(),
59+ new TimeOnlyConverter(),
60+ IsoDateTimeOffsetConverter.Singleton
61+ },
62+ };
63+ }
64+
65+ public class DateOnlyConverter : JsonConverter<DateOnly>
66+ {
67+ private readonly string serializationFormat;
68+ public DateOnlyConverter() : this(null) { }
69+
70+ public DateOnlyConverter(string? serializationFormat)
71+ {
72+ this.serializationFormat = serializationFormat ?? "yyyy-MM-dd";
73+ }
74+
75+ public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
76+ {
77+ var value = reader.GetString();
78+ return DateOnly.Parse(value!);
79+ }
80+
81+ public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
82+ => writer.WriteStringValue(value.ToString(serializationFormat));
83+ }
84+
85+ public class TimeOnlyConverter : JsonConverter<TimeOnly>
86+ {
87+ private readonly string serializationFormat;
88+
89+ public TimeOnlyConverter() : this(null) { }
90+
91+ public TimeOnlyConverter(string? serializationFormat)
92+ {
93+ this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff";
94+ }
95+
96+ public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
97+ {
98+ var value = reader.GetString();
99+ return TimeOnly.Parse(value!);
100+ }
101+
102+ public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options)
103+ => writer.WriteStringValue(value.ToString(serializationFormat));
104+ }
105+
106+ internal class IsoDateTimeOffsetConverter : JsonConverter<DateTimeOffset>
107+ {
108+ public override bool CanConvert(Type t) => t == typeof(DateTimeOffset);
109+
110+ private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
111+
112+ private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind;
113+ private string? _dateTimeFormat;
114+ private CultureInfo? _culture;
115+
116+ public DateTimeStyles DateTimeStyles
117+ {
118+ get => _dateTimeStyles;
119+ set => _dateTimeStyles = value;
120+ }
121+
122+ public string? DateTimeFormat
123+ {
124+ get => _dateTimeFormat ?? string.Empty;
125+ set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value;
126+ }
127+
128+ public CultureInfo Culture
129+ {
130+ get => _culture ?? CultureInfo.CurrentCulture;
131+ set => _culture = value;
132+ }
133+
134+ public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
135+ {
136+ string text;
137+
138+
139+ if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
140+ || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
141+ {
142+ value = value.ToUniversalTime();
143+ }
144+
145+ text = value.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
146+
147+ writer.WriteStringValue(text);
148+ }
149+
150+ public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
151+ {
152+ string? dateText = reader.GetString();
153+
154+ if (string.IsNullOrEmpty(dateText) == false)
155+ {
156+ if (!string.IsNullOrEmpty(_dateTimeFormat))
157+ {
158+ return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
159+ }
160+ else
161+ {
162+ return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles);
163+ }
164+ }
165+ else
166+ {
167+ return default(DateTimeOffset);
168+ }
169+ }
170+
171+
172+ public static readonly IsoDateTimeOffsetConverter Singleton = new IsoDateTimeOffsetConverter();
173+ }
174+}
175+#pragma warning restore CS8618
176+#pragma warning restore CS8601
177+#pragma warning restore CS8602
178+#pragma warning restore CS8603
Acsharpdefault / QuickType.cs+70 −0
@@ -0,0 +1,70 @@
1+// <auto-generated />
2+//
3+// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
4+//
5+// using QuickType;
6+//
7+// var topLevel = TopLevel.FromJson(jsonString);
8+#nullable enable
9+#pragma warning disable CS8618
10+#pragma warning disable CS8601
11+#pragma warning disable CS8602
12+#pragma warning disable CS8603
13+#pragma warning disable CS8604
14+#pragma warning disable CS8625
15+#pragma warning disable CS8765
16+
17+namespace QuickType
18+{
19+ using System;
20+ using System.Collections.Generic;
21+
22+ using System.Globalization;
23+ using Newtonsoft.Json;
24+ using Newtonsoft.Json.Converters;
25+
26+ public partial class TopLevel
27+ {
28+ [JsonProperty("hashCode", Required = Required.Always)]
29+ public string HashCode { get; set; }
30+
31+ [JsonProperty("noSuchMethod", Required = Required.Always)]
32+ public string NoSuchMethod { get; set; }
33+
34+ [JsonProperty("runtimeType", Required = Required.Always)]
35+ public long RuntimeType { get; set; }
36+
37+ [JsonProperty("toString", Required = Required.Always)]
38+ public bool TopLevelToString { get; set; }
39+ }
40+
41+ public partial class TopLevel
42+ {
43+ public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings);
44+ }
45+
46+ public static partial class Serialize
47+ {
48+ public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
49+ }
50+
51+ internal static partial class Converter
52+ {
53+ public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
54+ {
55+ MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
56+ DateParseHandling = DateParseHandling.None,
57+ Converters =
58+ {
59+ new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
60+ },
61+ };
62+ }
63+}
64+#pragma warning restore CS8618
65+#pragma warning restore CS8601
66+#pragma warning restore CS8602
67+#pragma warning restore CS8603
68+#pragma warning restore CS8604
69+#pragma warning restore CS8625
70+#pragma warning restore CS8765
Adartdefault / TopLevel.dart+37 −0
@@ -0,0 +1,37 @@
1+// To parse this JSON data, do
2+//
3+// final topLevel = topLevelFromJson(jsonString);
4+
5+import 'dart:convert';
6+
7+TopLevel topLevelFromJson(String str) => TopLevel.fromJson(json.decode(str));
8+
9+String topLevelToJson(TopLevel data) => json.encode(data.toJson());
10+
11+class TopLevel {
12+ final String topLevelHashCode;
13+ final String topLevelNoSuchMethod;
14+ final int topLevelRuntimeType;
15+ final bool topLevelToString;
16+
17+ TopLevel({
18+ required this.topLevelHashCode,
19+ required this.topLevelNoSuchMethod,
20+ required this.topLevelRuntimeType,
21+ required this.topLevelToString,
22+ });
23+
24+ factory TopLevel.fromJson(Map<String, dynamic> json) => TopLevel(
25+ topLevelHashCode: json["hashCode"],
26+ topLevelNoSuchMethod: json["noSuchMethod"],
27+ topLevelRuntimeType: json["runtimeType"],
28+ topLevelToString: json["toString"],
29+ );
30+
31+ Map<String, dynamic> toJson() => {
32+ "hashCode": topLevelHashCode,
33+ "noSuchMethod": topLevelNoSuchMethod,
34+ "runtimeType": topLevelRuntimeType,
35+ "toString": topLevelToString,
36+ };
37+}
Aelixirdefault / QuickType.ex+72 −0
@@ -0,0 +1,72 @@
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 TopLevel do
9+ @enforce_keys [:hash_code, :no_such_method, :runtime_type, :to_string]
10+ defstruct [:hash_code, :no_such_method, :runtime_type, :to_string]
11+
12+ @type t :: %__MODULE__{
13+ hash_code: String.t(),
14+ no_such_method: String.t(),
15+ runtime_type: integer(),
16+ to_string: boolean()
17+ }
18+
19+ def decode_hash_code(value) when is_binary(value), do: value
20+ def decode_hash_code(_), do: {:error, "Unexpected type when decoding TopLevel.hash_code"}
21+
22+ def encode_hash_code(value) when is_binary(value), do: value
23+ def encode_hash_code(_), do: {:error, "Unexpected type when encoding TopLevel.hash_code"}
24+
25+ def decode_no_such_method(value) when is_binary(value), do: value
26+ def decode_no_such_method(_), do: {:error, "Unexpected type when decoding TopLevel.no_such_method"}
27+
28+ def encode_no_such_method(value) when is_binary(value), do: value
29+ def encode_no_such_method(_), do: {:error, "Unexpected type when encoding TopLevel.no_such_method"}
30+
31+ def decode_runtime_type(value) when is_integer(value), do: value
32+ def decode_runtime_type(_), do: {:error, "Unexpected type when decoding TopLevel.runtime_type"}
33+
34+ def encode_runtime_type(value) when is_integer(value), do: value
35+ def encode_runtime_type(_), do: {:error, "Unexpected type when encoding TopLevel.runtime_type"}
36+
37+ def decode_to_string(value) when is_boolean(value), do: value
38+ def decode_to_string(_), do: {:error, "Unexpected type when decoding TopLevel.to_string"}
39+
40+ def encode_to_string(value) when is_boolean(value), do: value
41+ def encode_to_string(_), do: {:error, "Unexpected type when encoding TopLevel.to_string"}
42+
43+ def from_map(m) do
44+ %TopLevel{
45+ hash_code: decode_hash_code(m["hashCode"]),
46+ no_such_method: decode_no_such_method(m["noSuchMethod"]),
47+ runtime_type: decode_runtime_type(m["runtimeType"]),
48+ to_string: decode_to_string(m["toString"]),
49+ }
50+ end
51+
52+ def from_json(json) do
53+ json
54+ |> Jason.decode!()
55+ |> from_map()
56+ end
57+
58+ def to_map(struct) do
59+ %{
60+ "hashCode" => struct.hash_code,
61+ "noSuchMethod" => struct.no_such_method,
62+ "runtimeType" => struct.runtime_type,
63+ "toString" => struct.to_string,
64+ }
65+ end
66+
67+ def to_json(struct) do
68+ struct
69+ |> to_map()
70+ |> Jason.encode!()
71+ end
72+end
Aelmdefault / QuickType.elm+66 −0
@@ -0,0 +1,66 @@
1+-- To decode the JSON data, add this file to your project, run
2+--
3+-- elm install NoRedInk/elm-json-decode-pipeline
4+--
5+-- add these imports
6+--
7+-- import Json.Decode exposing (decodeString)
8+-- import QuickType exposing (quickType)
9+--
10+-- and you're off to the races with
11+--
12+-- decodeString quickType myJsonString
13+
14+module QuickType exposing
15+ ( QuickType
16+ , quickTypeToString
17+ , quickType
18+ )
19+
20+import Json.Decode as Jdec
21+import Json.Decode.Pipeline as Jpipe
22+import Json.Encode as Jenc
23+import Dict exposing (Dict)
24+
25+type alias QuickType =
26+ { hashCode : String
27+ , noSuchMethod : String
28+ , runtimeType : Int
29+ , toString : Bool
30+ }
31+
32+-- decoders and encoders
33+optionalField key decoder fallback =
34+ Jdec.dict Jdec.value
35+ |> Jdec.andThen (\m ->
36+ case Dict.get key m of
37+ Nothing -> Jdec.succeed fallback
38+ Just x -> Jdec.decodeValue decoder x |> Result.map Jdec.succeed |> Result.withDefault (Jdec.fail ("Invalid " ++ key)))
39+
40+quickTypeToString : QuickType -> String
41+quickTypeToString r = Jenc.encode 0 (encodeQuickType r)
42+
43+quickType : Jdec.Decoder QuickType
44+quickType =
45+ Jdec.succeed QuickType
46+ |> Jpipe.required "hashCode" Jdec.string
47+ |> Jpipe.required "noSuchMethod" Jdec.string
48+ |> Jpipe.required "runtimeType" Jdec.int
49+ |> Jpipe.required "toString" Jdec.bool
50+
51+encodeQuickType : QuickType -> Jenc.Value
52+encodeQuickType x =
53+ Jenc.object
54+ [ ("hashCode", Jenc.string x.hashCode)
55+ , ("noSuchMethod", Jenc.string x.noSuchMethod)
56+ , ("runtimeType", Jenc.int x.runtimeType)
57+ , ("toString", Jenc.bool x.toString)
58+ ]
59+
60+--- encoder helpers
61+
62+makeNullableEncoder : (a -> Jenc.Value) -> Maybe a -> Jenc.Value
63+makeNullableEncoder f m =
64+ case m of
65+ Just x -> f x
66+ Nothing -> Jenc.null
Aflowdefault / TopLevel.js+215 −0
@@ -0,0 +1,215 @@
1+// @flow
2+
3+// To parse this data:
4+//
5+// const Convert = require("./TopLevel");
6+//
7+// const topLevel = Convert.toTopLevel(json);
8+//
9+// These functions will throw an error if the JSON doesn't
10+// match the expected interface, even if the JSON is valid.
11+
12+export type TopLevel = {
13+ hashCode: string;
14+ noSuchMethod: string;
15+ runtimeType: number;
16+ toString: boolean;
17+};
18+
19+// Converts JSON strings to/from your types
20+// and asserts the results of JSON.parse at runtime
21+function toTopLevel(json: string): TopLevel {
22+ return cast(JSON.parse(json), r("TopLevel"));
23+}
24+
25+function topLevelToJson(value: TopLevel): string {
26+ return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
27+}
28+
29+function invalidValue(typ: any, val: any, key: any, parent: any = '') {
30+ const prettyTyp = prettyTypeName(typ);
31+ const parentText = parent ? ` on ${parent}` : '';
32+ const keyText = key ? ` for key "${key}"` : '';
33+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
34+}
35+
36+function prettyTypeName(typ: any): string {
37+ if (Array.isArray(typ)) {
38+ if (typ.length === 2 && typ[0] === undefined) {
39+ return `an optional ${prettyTypeName(typ[1])}`;
40+ } else {
41+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
42+ }
43+ } else if (typeof typ === "object" && typ.literal !== undefined) {
44+ return typ.literal;
45+ } else {
46+ return typeof typ;
47+ }
48+}
49+
50+function jsonToJSProps(typ: any): any {
51+ if (typ.jsonToJS === undefined) {
52+ const map: any = {};
53+ typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
54+ typ.jsonToJS = map;
55+ }
56+ return typ.jsonToJS;
57+}
58+
59+function jsToJSONProps(typ: any): any {
60+ if (typ.jsToJSON === undefined) {
61+ const map: any = {};
62+ typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
63+ typ.jsToJSON = map;
64+ }
65+ return typ.jsToJSON;
66+}
67+
68+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
69+ function transformPrimitive(typ: string, val: any): any {
70+ if (typeof typ === typeof val) return val;
71+ return invalidValue(typ, val, key, parent);
72+ }
73+
74+ function transformUnion(typs: any[], val: any): any {
75+ // val must validate against one typ in typs
76+ const l = typs.length;
77+ for (let i = 0; i < l; i++) {
78+ const typ = typs[i];
79+ try {
80+ return transform(val, typ, getProps);
81+ } catch (_) {}
82+ }
83+ return invalidValue(typs, val, key, parent);
84+ }
85+
86+ function transformEnum(cases: string[], val: any): any {
87+ if (cases.indexOf(val) !== -1) return val;
88+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
89+ }
90+
91+ function transformArray(typ: any, val: any): any {
92+ // val must be an array with no invalid elements
93+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
94+
95+ return val.map(el => transform(el, typ, getProps));
96+ }
97+
98+ function transformDate(val: any): any {
99+ if (val === null) {
100+ return null;
101+ }
102+ const d = new Date(val);
103+ if (isNaN(d.valueOf())) {
104+ return invalidValue(l("Date"), val, key, parent);
105+ }
106+ return d;
107+ }
108+
109+ function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
110+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
111+ return invalidValue(l(ref || "object"), val, key, parent);
112+ }
113+ const result: any = {};
114+ Object.getOwnPropertyNames(props).forEach(key => {
115+ const prop = props[key];
116+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
117+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
118+ });
119+ Object.getOwnPropertyNames(val).forEach(key => {
120+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
121+ result[key] = transform(val[key], additional, getProps, key, ref);
122+ }
123+ });
124+ return result;
125+ }
126+
127+ if (typ === "any") return val;
128+ if (typ === null) {
129+ if (val === null) return val;
130+ return invalidValue(typ, val, key, parent);
131+ }
132+ if (typ === false) return invalidValue(typ, val, key, parent);
133+ let ref: any = undefined;
134+ while (typeof typ === "object" && typ.ref !== undefined) {
135+ ref = typ.ref;
136+ typ = typeMap[typ.ref];
137+ }
138+ if (Array.isArray(typ)) return transformEnum(typ, val);
139+ if (typeof typ === "object") {
140+ return typ.hasOwnProperty("pattern") ? typeof val === "string" && new RegExp(typ.pattern).test(val) ? val : invalidValue(typ, val, key, parent)
141+ : typ.hasOwnProperty("string") ? typeof val === "string" && (typ.min === undefined || val.length >= typ.min) && (typ.max === undefined || val.length <= typ.max) ? transform(val, typ.string, getProps, key, parent) : invalidValue(typ, val, key, parent)
142+ : typ.hasOwnProperty("number") ? typeof val === "number" && (typ.min === undefined || val >= typ.min) && (typ.max === undefined || val <= typ.max) ? transform(val, typ.number, getProps, key, parent) : invalidValue(typ, val, key, parent)
143+ : typ.hasOwnProperty("integer") ? typeof val === "number" && val % 1 === 0 ? val : invalidValue(l("integer"), val, key, parent)
144+ : typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
145+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
146+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
147+ : invalidValue(typ, val, key, parent);
148+ }
149+ // Numbers can be parsed by Date but shouldn't be.
150+ if (typ === Date && typeof val !== "number") return transformDate(val);
151+ return transformPrimitive(typ, val);
152+}
153+
154+function cast<T>(val: any, typ: any): T {
155+ return transform(val, typ, jsonToJSProps);
156+}
157+
158+function uncast<T>(val: T, typ: any): any {
159+ return transform(val, typ, jsToJSONProps);
160+}
161+
162+function l(typ: any) {
163+ return { literal: typ };
164+}
165+
166+function a(typ: any) {
167+ return { arrayItems: typ };
168+}
169+
170+function i(typ: any) {
171+ return { integer: typ };
172+}
173+
174+function p(pattern: any) {
175+ return { pattern };
176+}
177+
178+function s(typ: any, min: any, max: any) {
179+ return { string: typ, min, max };
180+}
181+
182+function n(typ: any, min: any, max: any) {
183+ return { number: typ, min, max };
184+}
185+
186+function u(...typs: any[]) {
187+ return { unionMembers: typs };
188+}
189+
190+function o(props: any[], additional: any) {
191+ return { props, additional };
192+}
193+
194+function m(additional: any) {
195+ const props: any[] = [];
196+ return { props, additional };
197+}
198+
199+function r(name: string) {
200+ return { ref: name };
201+}
202+
203+const typeMap: any = {
204+ "TopLevel": o([
205+ { json: "hashCode", js: "hashCode", typ: "" },
206+ { json: "noSuchMethod", js: "noSuchMethod", typ: "" },
207+ { json: "runtimeType", js: "runtimeType", typ: i(0) },
208+ { json: "toString", js: "toString", typ: true },
209+ ], false),
210+};
211+
212+module.exports = {
213+ "topLevelToJson": topLevelToJson,
214+ "toTopLevel": toTopLevel,
215+};
Agolangdefault / quicktype.go+26 −0
@@ -0,0 +1,26 @@
1+// Code generated from JSON Schema using quicktype. DO NOT EDIT.
2+// To parse and unparse this JSON data, add this code to your project and do:
3+//
4+// topLevel, err := UnmarshalTopLevel(bytes)
5+// bytes, err = topLevel.Marshal()
6+
7+package main
8+
9+import "encoding/json"
10+
11+func UnmarshalTopLevel(data []byte) (TopLevel, error) {
12+ var r TopLevel
13+ err := json.Unmarshal(data, &r)
14+ return r, err
15+}
16+
17+func (r *TopLevel) Marshal() ([]byte, error) {
18+ return json.Marshal(r)
19+}
20+
21+type TopLevel struct {
22+ HashCode string `json:"hashCode"`
23+ NoSuchMethod string `json:"noSuchMethod"`
24+ RuntimeType int64 `json:"runtimeType"`
25+ ToString bool `json:"toString"`
26+}
Ahaskelldefault / QuickType.hs+39 −0
@@ -0,0 +1,39 @@
1+{-# LANGUAGE StrictData #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+
4+module QuickType
5+ ( QuickType (..)
6+ , decodeTopLevel
7+ ) where
8+
9+import Data.Aeson
10+import Data.Aeson.Types (emptyObject)
11+import Data.ByteString.Lazy (ByteString)
12+import Data.HashMap.Strict (HashMap)
13+import Data.Text (Text)
14+
15+data QuickType = QuickType
16+ { hashCodeQuickType :: Text
17+ , noSuchMethodQuickType :: Text
18+ , runtimeTypeQuickType :: Int
19+ , toStringQuickType :: Bool
20+ } deriving (Show)
21+
22+decodeTopLevel :: ByteString -> Maybe QuickType
23+decodeTopLevel = decode
24+
25+instance ToJSON QuickType where
26+ toJSON (QuickType hashCodeQuickType noSuchMethodQuickType runtimeTypeQuickType toStringQuickType) =
27+ object
28+ [ "hashCode" .= hashCodeQuickType
29+ , "noSuchMethod" .= noSuchMethodQuickType
30+ , "runtimeType" .= runtimeTypeQuickType
31+ , "toString" .= toStringQuickType
32+ ]
33+
34+instance FromJSON QuickType where
35+ parseJSON (Object v) = QuickType
36+ <$> v .: "hashCode"
37+ <*> v .: "noSuchMethod"
38+ <*> v .: "runtimeType"
39+ <*> v .: "toString"
Ajava-datetime-legacydefault / src / main / java / io / quicktype / Converter.java+124 −0
@@ -0,0 +1,124 @@
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 com.fasterxml.jackson.core.type.TypeReference;
23+import java.util.*;
24+import java.util.Date;
25+import java.text.SimpleDateFormat;
26+
27+public class Converter {
28+ // Date-time helpers
29+
30+ private static final String[] DATE_TIME_FORMATS = {
31+ "yyyy-MM-dd'T'HH:mm:ss.SX",
32+ "yyyy-MM-dd'T'HH:mm:ss.S",
33+ "yyyy-MM-dd'T'HH:mm:ssX",
34+ "yyyy-MM-dd'T'HH:mm:ss",
35+ "yyyy-MM-dd HH:mm:ss.SX",
36+ "yyyy-MM-dd HH:mm:ss.S",
37+ "yyyy-MM-dd HH:mm:ssX",
38+ "yyyy-MM-dd HH:mm:ss",
39+ "HH:mm:ss.SZ",
40+ "HH:mm:ss.S",
41+ "HH:mm:ssZ",
42+ "HH:mm:ss",
43+ "yyyy-MM-dd",
44+ };
45+
46+ public static Date parseAllDateTimeString(String str) {
47+ str = str.replaceFirst("(\\.\\d{3})\\d+", "$1");
48+ for (String format : DATE_TIME_FORMATS) {
49+ try {
50+ return new SimpleDateFormat(format).parse(str);
51+ } catch (Exception ex) {
52+ // Ignored
53+ }
54+ }
55+ return null;
56+ }
57+
58+ public static String serializeDateTime(Date datetime) {
59+ return new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ").format(datetime);
60+ }
61+
62+ public static String serializeDate(Date datetime) {
63+ return new SimpleDateFormat("yyyy-MM-dd").format(datetime);
64+ }
65+
66+ public static String serializeTime(Date datetime) {
67+ return new SimpleDateFormat("hh:mm:ssZ").format(datetime);
68+ }
69+ // Serialize/deserialize helpers
70+
71+ public static TopLevel fromJsonString(String json) throws IOException {
72+ return getObjectReader().readValue(json);
73+ }
74+
75+ public static String toJsonString(TopLevel obj) throws JsonProcessingException {
76+ return getObjectWriter().writeValueAsString(obj);
77+ }
78+
79+ private static ObjectReader reader;
80+ private static ObjectWriter writer;
81+
82+ private static void instantiateMapper() {
83+ ObjectMapper mapper = new ObjectMapper();
84+ mapper.findAndRegisterModules();
85+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
86+ mapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, false);
87+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
88+ SimpleModule module = new SimpleModule();
89+ module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
90+ @Override
91+ public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
92+ String value = jsonParser.getText();
93+ return Converter.parseAllDateTimeString(value);
94+ }
95+ });
96+ module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
97+ @Override
98+ public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
99+ String value = jsonParser.getText();
100+ return Converter.parseAllDateTimeString(value);
101+ }
102+ });
103+ module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
104+ @Override
105+ public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
106+ String value = jsonParser.getText();
107+ return Converter.parseAllDateTimeString(value);
108+ }
109+ });
110+ mapper.registerModule(module);
111+ reader = mapper.readerFor(TopLevel.class);
112+ writer = mapper.writerFor(TopLevel.class);
113+ }
114+
115+ private static ObjectReader getObjectReader() {
116+ if (reader == null) instantiateMapper();
117+ return reader;
118+ }
119+
120+ private static ObjectWriter getObjectWriter() {
121+ if (writer == null) instantiateMapper();
122+ return writer;
123+ }
124+}
Ajava-datetime-legacydefault / src / main / java / io / quicktype / TopLevel.java+30 −0
@@ -0,0 +1,30 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class TopLevel {
6+ private String hashCode;
7+ private String noSuchMethod;
8+ private long runtimeType;
9+ private boolean toString;
10+
11+ @JsonProperty("hashCode")
12+ public String getHashCode() { return hashCode; }
13+ @JsonProperty("hashCode")
14+ public void setHashCode(String value) { this.hashCode = value; }
15+
16+ @JsonProperty("noSuchMethod")
17+ public String getNoSuchMethod() { return noSuchMethod; }
18+ @JsonProperty("noSuchMethod")
19+ public void setNoSuchMethod(String value) { this.noSuchMethod = value; }
20+
21+ @JsonProperty("runtimeType")
22+ public long getRuntimeType() { return runtimeType; }
23+ @JsonProperty("runtimeType")
24+ public void setRuntimeType(long value) { this.runtimeType = value; }
25+
26+ @JsonProperty("toString")
27+ public boolean getToString() { return toString; }
28+ @JsonProperty("toString")
29+ public void setToString(boolean value) { this.toString = value; }
30+}
Ajava-lombokdefault / src / main / java / io / quicktype / Converter.java+103 −0
@@ -0,0 +1,103 @@
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 com.fasterxml.jackson.core.type.TypeReference;
23+import java.util.*;
24+import java.time.LocalDate;
25+import java.time.OffsetDateTime;
26+import java.time.OffsetTime;
27+import java.time.ZoneOffset;
28+import java.time.ZonedDateTime;
29+import java.time.format.DateTimeFormatter;
30+import java.time.format.DateTimeFormatterBuilder;
31+import java.time.temporal.ChronoField;
32+
33+public class Converter {
34+ // Date-time helpers
35+
36+ private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
37+ .appendOptional(DateTimeFormatter.ISO_DATE_TIME)
38+ .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
39+ .appendOptional(DateTimeFormatter.ISO_INSTANT)
40+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX"))
41+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX"))
42+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
43+ .toFormatter()
44+ .withZone(ZoneOffset.UTC);
45+
46+ public static OffsetDateTime parseDateTimeString(String str) {
47+ return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();
48+ }
49+
50+ private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
51+ .appendOptional(DateTimeFormatter.ISO_TIME)
52+ .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)
53+ .parseDefaulting(ChronoField.YEAR, 2020)
54+ .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
55+ .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
56+ .toFormatter()
57+ .withZone(ZoneOffset.UTC);
58+
59+ public static OffsetTime parseTimeString(String str) {
60+ return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();
61+ }
62+ // Serialize/deserialize helpers
63+
64+ public static TopLevel fromJsonString(String json) throws IOException {
65+ return getObjectReader().readValue(json);
66+ }
67+
68+ public static String toJsonString(TopLevel obj) throws JsonProcessingException {
69+ return getObjectWriter().writeValueAsString(obj);
70+ }
71+
72+ private static ObjectReader reader;
73+ private static ObjectWriter writer;
74+
75+ private static void instantiateMapper() {
76+ ObjectMapper mapper = new ObjectMapper();
77+ mapper.findAndRegisterModules();
78+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
79+ mapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, false);
80+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
81+ SimpleModule module = new SimpleModule();
82+ module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
83+ @Override
84+ public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
85+ String value = jsonParser.getText();
86+ return Converter.parseDateTimeString(value);
87+ }
88+ });
89+ mapper.registerModule(module);
90+ reader = mapper.readerFor(TopLevel.class);
91+ writer = mapper.writerFor(TopLevel.class);
92+ }
93+
94+ private static ObjectReader getObjectReader() {
95+ if (reader == null) instantiateMapper();
96+ return reader;
97+ }
98+
99+ private static ObjectWriter getObjectWriter() {
100+ if (writer == null) instantiateMapper();
101+ return writer;
102+ }
103+}
Ajava-lombokdefault / src / main / java / io / quicktype / TopLevel.java+30 −0
@@ -0,0 +1,30 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class TopLevel {
6+ private String hashCode;
7+ private String noSuchMethod;
8+ private long runtimeType;
9+ private boolean toString;
10+
11+ @JsonProperty("hashCode")
12+ public String getHashCode() { return hashCode; }
13+ @JsonProperty("hashCode")
14+ public void setHashCode(String value) { this.hashCode = value; }
15+
16+ @JsonProperty("noSuchMethod")
17+ public String getNoSuchMethod() { return noSuchMethod; }
18+ @JsonProperty("noSuchMethod")
19+ public void setNoSuchMethod(String value) { this.noSuchMethod = value; }
20+
21+ @JsonProperty("runtimeType")
22+ public long getRuntimeType() { return runtimeType; }
23+ @JsonProperty("runtimeType")
24+ public void setRuntimeType(long value) { this.runtimeType = value; }
25+
26+ @JsonProperty("toString")
27+ public boolean getToString() { return toString; }
28+ @JsonProperty("toString")
29+ public void setToString(boolean value) { this.toString = value; }
30+}
Ajavadefault / src / main / java / io / quicktype / Converter.java+103 −0
@@ -0,0 +1,103 @@
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 com.fasterxml.jackson.core.type.TypeReference;
23+import java.util.*;
24+import java.time.LocalDate;
25+import java.time.OffsetDateTime;
26+import java.time.OffsetTime;
27+import java.time.ZoneOffset;
28+import java.time.ZonedDateTime;
29+import java.time.format.DateTimeFormatter;
30+import java.time.format.DateTimeFormatterBuilder;
31+import java.time.temporal.ChronoField;
32+
33+public class Converter {
34+ // Date-time helpers
35+
36+ private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
37+ .appendOptional(DateTimeFormatter.ISO_DATE_TIME)
38+ .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
39+ .appendOptional(DateTimeFormatter.ISO_INSTANT)
40+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX"))
41+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX"))
42+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
43+ .toFormatter()
44+ .withZone(ZoneOffset.UTC);
45+
46+ public static OffsetDateTime parseDateTimeString(String str) {
47+ return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();
48+ }
49+
50+ private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
51+ .appendOptional(DateTimeFormatter.ISO_TIME)
52+ .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)
53+ .parseDefaulting(ChronoField.YEAR, 2020)
54+ .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
55+ .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
56+ .toFormatter()
57+ .withZone(ZoneOffset.UTC);
58+
59+ public static OffsetTime parseTimeString(String str) {
60+ return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();
61+ }
62+ // Serialize/deserialize helpers
63+
64+ public static TopLevel fromJsonString(String json) throws IOException {
65+ return getObjectReader().readValue(json);
66+ }
67+
68+ public static String toJsonString(TopLevel obj) throws JsonProcessingException {
69+ return getObjectWriter().writeValueAsString(obj);
70+ }
71+
72+ private static ObjectReader reader;
73+ private static ObjectWriter writer;
74+
75+ private static void instantiateMapper() {
76+ ObjectMapper mapper = new ObjectMapper();
77+ mapper.findAndRegisterModules();
78+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
79+ mapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, false);
80+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
81+ SimpleModule module = new SimpleModule();
82+ module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
83+ @Override
84+ public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
85+ String value = jsonParser.getText();
86+ return Converter.parseDateTimeString(value);
87+ }
88+ });
89+ mapper.registerModule(module);
90+ reader = mapper.readerFor(TopLevel.class);
91+ writer = mapper.writerFor(TopLevel.class);
92+ }
93+
94+ private static ObjectReader getObjectReader() {
95+ if (reader == null) instantiateMapper();
96+ return reader;
97+ }
98+
99+ private static ObjectWriter getObjectWriter() {
100+ if (writer == null) instantiateMapper();
101+ return writer;
102+ }
103+}
Ajavadefault / src / main / java / io / quicktype / TopLevel.java+30 −0
@@ -0,0 +1,30 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class TopLevel {
6+ private String hashCode;
7+ private String noSuchMethod;
8+ private long runtimeType;
9+ private boolean toString;
10+
11+ @JsonProperty("hashCode")
12+ public String getHashCode() { return hashCode; }
13+ @JsonProperty("hashCode")
14+ public void setHashCode(String value) { this.hashCode = value; }
15+
16+ @JsonProperty("noSuchMethod")
17+ public String getNoSuchMethod() { return noSuchMethod; }
18+ @JsonProperty("noSuchMethod")
19+ public void setNoSuchMethod(String value) { this.noSuchMethod = value; }
20+
21+ @JsonProperty("runtimeType")
22+ public long getRuntimeType() { return runtimeType; }
23+ @JsonProperty("runtimeType")
24+ public void setRuntimeType(long value) { this.runtimeType = value; }
25+
26+ @JsonProperty("toString")
27+ public boolean getToString() { return toString; }
28+ @JsonProperty("toString")
29+ public void setToString(boolean value) { this.toString = value; }
30+}
Ajavascript-prop-typesdefault / toplevel.js+24 −0
@@ -0,0 +1,24 @@
1+// Example usage:
2+//
3+// import { MyShape } from ./myShape.js;
4+//
5+// class MyComponent extends React.Component {
6+// //
7+// }
8+//
9+// MyComponent.propTypes = {
10+// input: MyShape
11+// };
12+
13+import PropTypes from "prop-types";
14+const Integer = (props, name) => props[name] == null || Number.isInteger(props[name]) ? null : new Error("Expected integer");
15+
16+let _TopLevel;
17+_TopLevel = PropTypes.shape({
18+ "hashCode": PropTypes.oneOfType([PropTypes.string]).isRequired,
19+ "noSuchMethod": PropTypes.oneOfType([PropTypes.string]).isRequired,
20+ "runtimeType": PropTypes.oneOfType([Integer]).isRequired,
21+ "toString": PropTypes.oneOfType([PropTypes.bool]).isRequired,
22+});
23+
24+export const TopLevel = _TopLevel;
Ajavascriptdefault / TopLevel.js+206 −0
@@ -0,0 +1,206 @@
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+
86+ return val.map(el => transform(el, typ, getProps));
87+ }
88+
89+ function transformDate(val) {
90+ if (val === null) {
91+ return null;
92+ }
93+ const d = new Date(val);
94+ if (isNaN(d.valueOf())) {
95+ return invalidValue(l("Date"), val, key, parent);
96+ }
97+ return d;
98+ }
99+
100+ function transformObject(props, additional, val) {
101+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
102+ return invalidValue(l(ref || "object"), val, key, parent);
103+ }
104+ const result = {};
105+ Object.getOwnPropertyNames(props).forEach(key => {
106+ const prop = props[key];
107+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
108+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
109+ });
110+ Object.getOwnPropertyNames(val).forEach(key => {
111+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
112+ result[key] = transform(val[key], additional, getProps, key, ref);
113+ }
114+ });
115+ return result;
116+ }
117+
118+ if (typ === "any") return val;
119+ if (typ === null) {
120+ if (val === null) return val;
121+ return invalidValue(typ, val, key, parent);
122+ }
123+ if (typ === false) return invalidValue(typ, val, key, parent);
124+ let ref = undefined;
125+ while (typeof typ === "object" && typ.ref !== undefined) {
126+ ref = typ.ref;
127+ typ = typeMap[typ.ref];
128+ }
129+ if (Array.isArray(typ)) return transformEnum(typ, val);
130+ if (typeof typ === "object") {
131+ return typ.hasOwnProperty("pattern") ? typeof val === "string" && new RegExp(typ.pattern).test(val) ? val : invalidValue(typ, val, key, parent)
132+ : typ.hasOwnProperty("string") ? typeof val === "string" && (typ.min === undefined || val.length >= typ.min) && (typ.max === undefined || val.length <= typ.max) ? transform(val, typ.string, getProps, key, parent) : invalidValue(typ, val, key, parent)
133+ : typ.hasOwnProperty("number") ? typeof val === "number" && (typ.min === undefined || val >= typ.min) && (typ.max === undefined || val <= typ.max) ? transform(val, typ.number, getProps, key, parent) : invalidValue(typ, val, key, parent)
134+ : typ.hasOwnProperty("integer") ? typeof val === "number" && val % 1 === 0 ? val : invalidValue(l("integer"), val, key, parent)
135+ : typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
136+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
137+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
138+ : invalidValue(typ, val, key, parent);
139+ }
140+ // Numbers can be parsed by Date but shouldn't be.
141+ if (typ === Date && typeof val !== "number") return transformDate(val);
142+ return transformPrimitive(typ, val);
143+}
144+
145+function cast(val, typ) {
146+ return transform(val, typ, jsonToJSProps);
147+}
148+
149+function uncast(val, typ) {
150+ return transform(val, typ, jsToJSONProps);
151+}
152+
153+function l(typ) {
154+ return { literal: typ };
155+}
156+
157+function a(typ) {
158+ return { arrayItems: typ };
159+}
160+
161+function i(typ) {
162+ return { integer: typ };
163+}
164+
165+function p(pattern) {
166+ return { pattern };
167+}
168+
169+function s(typ, min, max) {
170+ return { string: typ, min, max };
171+}
172+
173+function n(typ, min, max) {
174+ return { number: typ, min, max };
175+}
176+
177+function u(...typs) {
178+ return { unionMembers: typs };
179+}
180+
181+function o(props, additional) {
182+ return { props, additional };
183+}
184+
185+function m(additional) {
186+ const props = [];
187+ return { props, additional };
188+}
189+
190+function r(name) {
191+ return { ref: name };
192+}
193+
194+const typeMap = {
195+ "TopLevel": o([
196+ { json: "hashCode", js: "hashCode", typ: "" },
197+ { json: "noSuchMethod", js: "noSuchMethod", typ: "" },
198+ { json: "runtimeType", js: "runtimeType", typ: i(0) },
199+ { json: "toString", js: "toString", typ: true },
200+ ], false),
201+};
202+
203+module.exports = {
204+ "topLevelToJson": topLevelToJson,
205+ "toTopLevel": toTopLevel,
206+};
Akotlin-jacksondefault / TopLevel.kt+40 −0
@@ -0,0 +1,40 @@
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 = object : PropertyNamingStrategy.PropertyNamingStrategyBase() { override fun translate(name: String) = if (name == "empty") "" else name }
18+ setSerializationInclusion(JsonInclude.Include.NON_NULL)
19+ disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT)
20+}
21+
22+data class TopLevel (
23+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
24+ val hashCode: String,
25+
26+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
27+ val noSuchMethod: String,
28+
29+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
30+ val runtimeType: Long,
31+
32+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
33+ val toString: Boolean
34+) {
35+ fun toJson() = mapper.writeValueAsString(this)
36+
37+ companion object {
38+ fun fromJson(json: String) = mapper.readValue<TopLevel>(json)
39+ }
40+}
Akotlindefault / TopLevel.kt+22 −0
@@ -0,0 +1,22 @@
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+data class TopLevel (
12+ val hashCode: String,
13+ val noSuchMethod: String,
14+ val runtimeType: Long,
15+ val toString: Boolean
16+) {
17+ public fun toJson() = klaxon.toJsonString(this)
18+
19+ companion object {
20+ public fun fromJson(json: String) = klaxon.parse<TopLevel>(json)
21+ }
22+}
Akotlinxdefault / TopLevel.kt+19 −0
@@ -0,0 +1,19 @@
1+// To parse the JSON, install kotlin's serialization plugin and do:
2+//
3+// val json = Json { allowStructuredMapKeys = true }
4+// val topLevel = json.parse(TopLevel.serializer(), jsonString)
5+
6+package quicktype
7+
8+import kotlinx.serialization.*
9+import kotlinx.serialization.json.*
10+import kotlinx.serialization.descriptors.*
11+import kotlinx.serialization.encoding.*
12+
13+@Serializable
14+data class TopLevel (
15+ val hashCode: String,
16+ val noSuchMethod: String,
17+ val runtimeType: Long,
18+ val toString: Boolean
19+)
Aobjective-cdefault / QTTopLevel.h+33 −0
@@ -0,0 +1,33 @@
1+// To parse this JSON:
2+//
3+// NSError *error;
4+// QTTopLevel *topLevel = [QTTopLevel fromJSON:json encoding:NSUTF8Encoding error:&error];
5+
6+#import <Foundation/Foundation.h>
7+
8+@class QTTopLevel;
9+
10+NS_ASSUME_NONNULL_BEGIN
11+
12+#pragma mark - Top-level marshaling functions
13+
14+QTTopLevel *_Nullable QTTopLevelFromData(NSData *data, NSError **error);
15+QTTopLevel *_Nullable QTTopLevelFromJSON(NSString *json, NSStringEncoding encoding, NSError **error);
16+NSData *_Nullable QTTopLevelToData(QTTopLevel *topLevel, NSError **error);
17+NSString *_Nullable QTTopLevelToJSON(QTTopLevel *topLevel, NSStringEncoding encoding, NSError **error);
18+
19+#pragma mark - Object interfaces
20+
21+@interface QTTopLevel : NSObject
22+@property (nonatomic, assign) BOOL isToString;
23+@property (nonatomic, copy) NSString *noSuchMethod;
24+@property (nonatomic, assign) NSInteger runtimeType;
25+@property (nonatomic, copy) NSString *theHashCode;
26+
27++ (_Nullable instancetype)fromJSON:(NSString *)json encoding:(NSStringEncoding)encoding error:(NSError *_Nullable *)error;
28++ (_Nullable instancetype)fromData:(NSData *)data error:(NSError *_Nullable *)error;
29+- (NSString *_Nullable)toJSON:(NSStringEncoding)encoding error:(NSError *_Nullable *)error;
30+- (NSData *_Nullable)toData:(NSError *_Nullable *)error;
31+@end
32+
33+NS_ASSUME_NONNULL_END
Aobjective-cdefault / QTTopLevel.m+134 −0
@@ -0,0 +1,134 @@
1+#import "QTTopLevel.h"
2+
3+#define λ(decl, expr) (^(decl) { return (expr); })
4+
5+static id NSNullify(id _Nullable x) {
6+ return (x == nil || x == NSNull.null) ? NSNull.null : x;
7+}
8+
9+NS_ASSUME_NONNULL_BEGIN
10+
11+@interface QTTopLevel (JSONConversion)
12++ (instancetype)fromJSONDictionary:(NSDictionary *)dict;
13+- (NSDictionary *)JSONDictionary;
14+@end
15+
16+#pragma mark - JSON serialization
17+
18+QTTopLevel *_Nullable QTTopLevelFromData(NSData *data, NSError **error)
19+{
20+ @try {
21+ id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:error];
22+ return *error ? nil : [QTTopLevel fromJSONDictionary:json];
23+ } @catch (NSException *exception) {
24+ *error = [NSError errorWithDomain:@"JSONSerialization" code:-1 userInfo:@{ @"exception": exception }];
25+ return nil;
26+ }
27+}
28+
29+QTTopLevel *_Nullable QTTopLevelFromJSON(NSString *json, NSStringEncoding encoding, NSError **error)
30+{
31+ return QTTopLevelFromData([json dataUsingEncoding:encoding], error);
32+}
33+
34+NSData *_Nullable QTTopLevelToData(QTTopLevel *topLevel, NSError **error)
35+{
36+ @try {
37+ id json = [topLevel JSONDictionary];
38+ NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingFragmentsAllowed error:error];
39+ return *error ? nil : data;
40+ } @catch (NSException *exception) {
41+ *error = [NSError errorWithDomain:@"JSONSerialization" code:-1 userInfo:@{ @"exception": exception }];
42+ return nil;
43+ }
44+}
45+
46+NSString *_Nullable QTTopLevelToJSON(QTTopLevel *topLevel, NSStringEncoding encoding, NSError **error)
47+{
48+ NSData *data = QTTopLevelToData(topLevel, error);
49+ return data ? [[NSString alloc] initWithData:data encoding:encoding] : nil;
50+}
51+
52+@implementation QTTopLevel
53++ (NSDictionary<NSString *, NSString *> *)properties
54+{
55+ static NSDictionary<NSString *, NSString *> *properties;
56+ return properties = properties ? properties : @{
57+ @"toString": @"isToString",
58+ @"noSuchMethod": @"noSuchMethod",
59+ @"runtimeType": @"runtimeType",
60+ @"hashCode": @"theHashCode",
61+ };
62+}
63+
64++ (_Nullable instancetype)fromData:(NSData *)data error:(NSError *_Nullable *)error
65+{
66+ return QTTopLevelFromData(data, error);
67+}
68+
69++ (_Nullable instancetype)fromJSON:(NSString *)json encoding:(NSStringEncoding)encoding error:(NSError *_Nullable *)error
70+{
71+ return QTTopLevelFromJSON(json, encoding, error);
72+}
73+
74++ (instancetype)fromJSONDictionary:(NSDictionary *)dict
75+{
76+ return [dict isKindOfClass:NSDictionary.class] ? [[QTTopLevel alloc] initWithJSONDictionary:dict] : nil;
77+}
78+
79+- (instancetype)initWithJSONDictionary:(NSDictionary *)dict
80+{
81+ if (self = [super init]) {
82+ if (![dict[@"toString"] isKindOfClass:NSNumber.class]) return nil;
83+ if (![dict[@"noSuchMethod"] isKindOfClass:NSString.class]) return nil;
84+ if (![dict[@"runtimeType"] isKindOfClass:NSNumber.class]) return nil;
85+ if ([dict[@"runtimeType"] doubleValue] != [dict[@"runtimeType"] longLongValue]) return nil;
86+ if (![dict[@"hashCode"] isKindOfClass:NSString.class]) return nil;
87+ [self setValuesForKeysWithDictionary:dict];
88+ }
89+ return self;
90+}
91+
92+- (void)setValue:(nullable id)value forKey:(NSString *)key
93+{
94+ id resolved = QTTopLevel.properties[key];
95+ if (resolved) [super setValue:value forKey:resolved];
96+}
97+
98+- (void)setNilValueForKey:(NSString *)key
99+{
100+ id resolved = QTTopLevel.properties[key];
101+ if (resolved) [super setValue:@(0) forKey:resolved];
102+}
103+
104+- (NSDictionary *)JSONDictionary
105+{
106+ id dict = [[self dictionaryWithValuesForKeys:QTTopLevel.properties.allValues] mutableCopy];
107+
108+ for (id jsonName in QTTopLevel.properties) {
109+ id propertyName = QTTopLevel.properties[jsonName];
110+ if (![jsonName isEqualToString:propertyName]) {
111+ dict[jsonName] = dict[propertyName];
112+ [dict removeObjectForKey:propertyName];
113+ }
114+ }
115+
116+ [dict addEntriesFromDictionary:@{
117+ @"toString": _isToString ? @YES : @NO,
118+ }];
119+
120+ return dict;
121+}
122+
123+- (NSData *_Nullable)toData:(NSError *_Nullable *)error
124+{
125+ return QTTopLevelToData(self, error);
126+}
127+
128+- (NSString *_Nullable)toJSON:(NSStringEncoding)encoding error:(NSError *_Nullable *)error
129+{
130+ return QTTopLevelToJSON(self, encoding, error);
131+}
132+@end
133+
134+NS_ASSUME_NONNULL_END
Aphpdefault / TopLevel.php+274 −0
@@ -0,0 +1,274 @@
1+<?php
2+declare(strict_types=1);
3+
4+// This is an autogenerated file:TopLevel
5+
6+class TopLevel {
7+ private string $hashCode; // json:hashCode Required
8+ private string $noSuchMethod; // json:noSuchMethod Required
9+ private int $runtimeType; // json:runtimeType Required
10+ private bool $toString; // json:toString Required
11+
12+ /**
13+ * @param string $hashCode
14+ * @param string $noSuchMethod
15+ * @param int $runtimeType
16+ * @param bool $toString
17+ */
18+ public function __construct(string $hashCode, string $noSuchMethod, int $runtimeType, bool $toString) {
19+ $this->hashCode = $hashCode;
20+ $this->noSuchMethod = $noSuchMethod;
21+ $this->runtimeType = $runtimeType;
22+ $this->toString = $toString;
23+ }
24+
25+ /**
26+ * @param string $value
27+ * @throws Exception
28+ * @return string
29+ */
30+ public static function fromHashCode(string $value): string {
31+ return $value; /*string*/
32+ }
33+
34+ /**
35+ * @throws Exception
36+ * @return string
37+ */
38+ public function toHashCode(): string {
39+ if (TopLevel::validateHashCode($this->hashCode)) {
40+ return $this->hashCode; /*string*/
41+ }
42+ throw new Exception('never get to this TopLevel::hashCode');
43+ }
44+
45+ /**
46+ * @param string
47+ * @return bool
48+ * @throws Exception
49+ */
50+ public static function validateHashCode(string $value): bool {
51+ return true;
52+ }
53+
54+ /**
55+ * @throws Exception
56+ * @return string
57+ */
58+ public function getHashCode(): string {
59+ if (TopLevel::validateHashCode($this->hashCode)) {
60+ return $this->hashCode;
61+ }
62+ throw new Exception('never get to getHashCode TopLevel::hashCode');
63+ }
64+
65+ /**
66+ * @return string
67+ */
68+ public static function sampleHashCode(): string {
69+ return 'TopLevel::hashCode::31'; /*31:hashCode*/
70+ }
71+
72+ /**
73+ * @param string $value
74+ * @throws Exception
75+ * @return string
76+ */
77+ public static function fromNoSuchMethod(string $value): string {
78+ return $value; /*string*/
79+ }
80+
81+ /**
82+ * @throws Exception
83+ * @return string
84+ */
85+ public function toNoSuchMethod(): string {
86+ if (TopLevel::validateNoSuchMethod($this->noSuchMethod)) {
87+ return $this->noSuchMethod; /*string*/
88+ }
89+ throw new Exception('never get to this TopLevel::noSuchMethod');
90+ }
91+
92+ /**
93+ * @param string
94+ * @return bool
95+ * @throws Exception
96+ */
97+ public static function validateNoSuchMethod(string $value): bool {
98+ return true;
99+ }
100+
101+ /**
102+ * @throws Exception
103+ * @return string
104+ */
105+ public function getNoSuchMethod(): string {
106+ if (TopLevel::validateNoSuchMethod($this->noSuchMethod)) {
107+ return $this->noSuchMethod;
108+ }
109+ throw new Exception('never get to getNoSuchMethod TopLevel::noSuchMethod');
110+ }
111+
112+ /**
113+ * @return string
114+ */
115+ public static function sampleNoSuchMethod(): string {
116+ return 'TopLevel::noSuchMethod::32'; /*32:noSuchMethod*/
117+ }
118+
119+ /**
120+ * @param int $value
121+ * @throws Exception
122+ * @return int
123+ */
124+ public static function fromRuntimeType(int $value): int {
125+ return $value; /*int*/
126+ }
127+
128+ /**
129+ * @throws Exception
130+ * @return int
131+ */
132+ public function toRuntimeType(): int {
133+ if (TopLevel::validateRuntimeType($this->runtimeType)) {
134+ return $this->runtimeType; /*int*/
135+ }
136+ throw new Exception('never get to this TopLevel::runtimeType');
137+ }
138+
139+ /**
140+ * @param int
141+ * @return bool
142+ * @throws Exception
143+ */
144+ public static function validateRuntimeType(int $value): bool {
145+ return true;
146+ }
147+
148+ /**
149+ * @throws Exception
150+ * @return int
151+ */
152+ public function getRuntimeType(): int {
153+ if (TopLevel::validateRuntimeType($this->runtimeType)) {
154+ return $this->runtimeType;
155+ }
156+ throw new Exception('never get to getRuntimeType TopLevel::runtimeType');
157+ }
158+
159+ /**
160+ * @return int
161+ */
162+ public static function sampleRuntimeType(): int {
163+ return 33; /*33:runtimeType*/
164+ }
165+
166+ /**
167+ * @param bool $value
168+ * @throws Exception
169+ * @return bool
170+ */
171+ public static function fromToString(bool $value): bool {
172+ return $value; /*bool*/
173+ }
174+
175+ /**
176+ * @throws Exception
177+ * @return bool
178+ */
179+ public function toToString(): bool {
180+ if (TopLevel::validateToString($this->toString)) {
181+ return $this->toString; /*bool*/
182+ }
183+ throw new Exception('never get to this TopLevel::toString');
184+ }
185+
186+ /**
187+ * @param bool
188+ * @return bool
189+ * @throws Exception
190+ */
191+ public static function validateToString(bool $value): bool {
192+ return true;
193+ }
194+
195+ /**
196+ * @throws Exception
197+ * @return bool
198+ */
199+ public function getToString(): bool {
200+ if (TopLevel::validateToString($this->toString)) {
201+ return $this->toString;
202+ }
203+ throw new Exception('never get to getToString TopLevel::toString');
204+ }
205+
206+ /**
207+ * @return bool
208+ */
209+ public static function sampleToString(): bool {
210+ return true; /*34:toString*/
211+ }
212+
213+ /**
214+ * @throws Exception
215+ * @return bool
216+ */
217+ public function validate(): bool {
218+ return TopLevel::validateHashCode($this->hashCode)
219+ || TopLevel::validateNoSuchMethod($this->noSuchMethod)
220+ || TopLevel::validateRuntimeType($this->runtimeType)
221+ || TopLevel::validateToString($this->toString);
222+ }
223+
224+ /**
225+ * @return stdClass
226+ * @throws Exception
227+ */
228+ public function to(): stdClass {
229+ $out = new stdClass();
230+ $out->{'hashCode'} = $this->toHashCode();
231+ $out->{'noSuchMethod'} = $this->toNoSuchMethod();
232+ $out->{'runtimeType'} = $this->toRuntimeType();
233+ $out->{'toString'} = $this->toToString();
234+ return $out;
235+ }
236+
237+ /**
238+ * @param stdClass $obj
239+ * @return TopLevel
240+ * @throws Exception
241+ */
242+ public static function from(stdClass $obj): TopLevel {
243+ if (!property_exists($obj, 'hashCode')) {
244+ throw new Exception("Missing required property");
245+ }
246+ if (!property_exists($obj, 'noSuchMethod')) {
247+ throw new Exception("Missing required property");
248+ }
249+ if (!property_exists($obj, 'runtimeType')) {
250+ throw new Exception("Missing required property");
251+ }
252+ if (!property_exists($obj, 'toString')) {
253+ throw new Exception("Missing required property");
254+ }
255+ return new TopLevel(
256+ TopLevel::fromHashCode($obj->{'hashCode'})
257+ ,TopLevel::fromNoSuchMethod($obj->{'noSuchMethod'})
258+ ,TopLevel::fromRuntimeType($obj->{'runtimeType'})
259+ ,TopLevel::fromToString($obj->{'toString'})
260+ );
261+ }
262+
263+ /**
264+ * @return TopLevel
265+ */
266+ public static function sample(): TopLevel {
267+ return new TopLevel(
268+ TopLevel::sampleHashCode()
269+ ,TopLevel::sampleNoSuchMethod()
270+ ,TopLevel::sampleRuntimeType()
271+ ,TopLevel::sampleToString()
272+ );
273+ }
274+}
Apikedefault / TopLevel.pmod+44 −0
@@ -0,0 +1,44 @@
1+// This source has been automatically generated by quicktype.
2+// ( https://github.com/quicktype/quicktype )
3+//
4+// To use this code, simply import it into your project as a Pike module.
5+// To JSON-encode your object, you can pass it to `Standards.JSON.encode`
6+// or call `encode_json` on it.
7+//
8+// To decode a JSON string, first pass it to `Standards.JSON.decode`,
9+// and then pass the result to `<YourClass>_from_JSON`.
10+// It will return an instance of <YourClass>.
11+// Bear in mind that these functions have unexpected behavior,
12+// and will likely throw an error, if the JSON string does not
13+// match the expected interface, even if the JSON itself is valid.
14+
15+class TopLevel {
16+ string hash_code; // json: "hashCode"
17+ string no_such_method; // json: "noSuchMethod"
18+ int runtime_type; // json: "runtimeType"
19+ bool to_string; // json: "toString"
20+
21+ string encode_json() {
22+ mapping(string:mixed) json = ([
23+ "hashCode" : hash_code,
24+ "noSuchMethod" : no_such_method,
25+ "runtimeType" : runtime_type,
26+ "toString" : to_string,
27+ ]);
28+
29+ return Standards.JSON.encode(json);
30+ }
31+}
32+
33+TopLevel TopLevel_from_JSON(mixed json) {
34+ TopLevel retval = TopLevel();
35+
36+ retval.hash_code = json["hashCode"];
37+ retval.no_such_method = json["noSuchMethod"];
38+ if (!intp(json["runtimeType"])) error("Expected integer");
39+ retval.runtime_type = json["runtimeType"];
40+ if (json["toString"] != Standards.JSON.true && json["toString"] != Standards.JSON.false) error("Expected bool");
41+ retval.to_string = json["toString"];
42+
43+ return retval;
44+}
Apythondefault / quicktype.py+58 −0
@@ -0,0 +1,58 @@
1+from dataclasses import dataclass
2+from typing import Any, TypeVar, Type, cast
3+
4+
5+T = TypeVar("T")
6+
7+
8+def from_str(x: Any) -> str:
9+ assert isinstance(x, str)
10+ return x
11+
12+
13+def from_int(x: Any) -> int:
14+ assert isinstance(x, int) and not isinstance(x, bool)
15+ return x
16+
17+
18+def from_bool(x: Any) -> bool:
19+ assert isinstance(x, bool)
20+ return x
21+
22+
23+def to_class(c: Type[T], x: Any) -> dict:
24+ assert isinstance(x, c)
25+ return cast(Any, x).to_dict()
26+
27+
28+@dataclass
29+class TopLevel:
30+ hash_code: str
31+ no_such_method: str
32+ runtime_type: int
33+ to_string: bool
34+
35+ @staticmethod
36+ def from_dict(obj: Any) -> 'TopLevel':
37+ assert isinstance(obj, dict)
38+ hash_code = from_str(obj.get("hashCode"))
39+ no_such_method = from_str(obj.get("noSuchMethod"))
40+ runtime_type = from_int(obj.get("runtimeType"))
41+ to_string = from_bool(obj.get("toString"))
42+ return TopLevel(hash_code, no_such_method, runtime_type, to_string)
43+
44+ def to_dict(self) -> dict:
45+ result: dict = {}
46+ result["hashCode"] = from_str(self.hash_code)
47+ result["noSuchMethod"] = from_str(self.no_such_method)
48+ result["runtimeType"] = from_int(self.runtime_type)
49+ result["toString"] = from_bool(self.to_string)
50+ return result
51+
52+
53+def top_level_from_dict(s: Any) -> TopLevel:
54+ return TopLevel.from_dict(s)
55+
56+
57+def top_level_to_dict(x: TopLevel) -> Any:
58+ return to_class(TopLevel, x)
Arubydefault / TopLevel.rb+56 −0
@@ -0,0 +1,56 @@
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.hash_code
8+#
9+# If from_json! succeeds, the value returned matches the schema.
10+
11+require 'json'
12+require 'dry-types'
13+require 'dry-struct'
14+
15+module Types
16+ include Dry.Types(default: :nominal)
17+
18+ Integer = Strict::Integer
19+ Bool = Strict::Bool
20+ Hash = Strict::Hash
21+ String = Strict::String
22+end
23+
24+class TopLevel < Dry::Struct
25+ attribute :hash_code, Types::String
26+ attribute :no_such_method, Types::String
27+ attribute :runtime_type, Types::Integer
28+ attribute :to_string, Types::Bool
29+
30+ def self.from_dynamic!(d)
31+ d = Types::Hash[d]
32+ new(
33+ hash_code: d.fetch("hashCode"),
34+ no_such_method: d.fetch("noSuchMethod"),
35+ runtime_type: d.fetch("runtimeType"),
36+ to_string: d.fetch("toString"),
37+ )
38+ end
39+
40+ def self.from_json!(json)
41+ from_dynamic!(JSON.parse(json))
42+ end
43+
44+ def to_dynamic
45+ {
46+ "hashCode" => hash_code,
47+ "noSuchMethod" => no_such_method,
48+ "runtimeType" => runtime_type,
49+ "toString" => to_string,
50+ }
51+ end
52+
53+ def to_json(options = nil)
54+ JSON.generate(to_dynamic, options)
55+ end
56+end
Arustdefault / module_under_test.rs+26 −0
@@ -0,0 +1,26 @@
1+// Example code that deserializes and serializes the model.
2+// extern crate serde;
3+// #[macro_use]
4+// extern crate serde_derive;
5+// extern crate serde_json;
6+//
7+// use generated_module::TopLevel;
8+//
9+// fn main() {
10+// let json = r#"{"answer": 42}"#;
11+// let model: TopLevel = serde_json::from_str(&json).unwrap();
12+// }
13+
14+use serde::{Serialize, Deserialize};
15+
16+#[derive(Debug, Clone, Serialize, Deserialize)]
17+#[serde(rename_all = "camelCase")]
18+pub struct TopLevel {
19+ pub hash_code: String,
20+
21+ pub no_such_method: String,
22+
23+ pub runtime_type: i64,
24+
25+ pub to_string: bool,
26+}
Ascala3-upickledefault / TopLevel.scala+77 −0
@@ -0,0 +1,77 @@
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+given OptionPickler.ReadWriter[java.time.Instant] = OptionPickler.readwriter[String].bimap(_.toString, java.time.Instant.parse)
29+
30+object JsonExt:
31+ val valueReader = OptionPickler.readwriter[ujson.Value]
32+
33+ // upickle's built-in primitive readers are lenient -- the numeric and
34+ // boolean readers accept strings, and the string reader accepts
35+ // numbers and booleans -- so untagged unions need strict readers to
36+ // pick the right member.
37+ val strictString: OptionPickler.Reader[String] = valueReader.map {
38+ case ujson.Str(s) => s
39+ case json => throw new upickle.core.Abort("expected string, got " + json)
40+ }
41+ val strictLong: OptionPickler.Reader[Long] = valueReader.map {
42+ case ujson.Num(n) if n.isWhole => n.toLong
43+ case json => throw new upickle.core.Abort("expected integer, got " + json)
44+ }
45+ val strictDouble: OptionPickler.Reader[Double] = valueReader.map {
46+ case ujson.Num(n) => n
47+ case json => throw new upickle.core.Abort("expected number, got " + json)
48+ }
49+ val strictBoolean: OptionPickler.Reader[Boolean] = valueReader.map {
50+ case ujson.Bool(b) => b
51+ case json => throw new upickle.core.Abort("expected boolean, got " + json)
52+ }
53+
54+ def badMerge[T](r1: => OptionPickler.Reader[?], rest: OptionPickler.Reader[?]*): OptionPickler.Reader[T] = valueReader.map { json =>
55+ var t: T | Null = null
56+ val stack = Vector.newBuilder[Throwable]
57+ (r1 +: rest).foreach { reader =>
58+ if t == null then
59+ try
60+ t = OptionPickler.read[T](json, trace = true)(using reader.asInstanceOf[OptionPickler.Reader[T]])
61+ catch
62+ case exc => stack += exc
63+ }
64+ if t != null then t.nn else throw new Exception(json.toString(), stack.result().headOption.getOrElse(null))
65+ }
66+end JsonExt
67+given OptionPickler.Reader[Long] = JsonExt.strictLong
68+
69+
70+case class TopLevel (
71+ @upickle.implicits.key("hashCode")
72+ val hashCodeValue : String,
73+ val noSuchMethod : String,
74+ val runtimeType : Long,
75+ @upickle.implicits.key("toString")
76+ val toStringValue : Boolean
77+) derives OptionPickler.ReadWriter
Ascala3default / TopLevel.scala+25 −0
@@ -0,0 +1,25 @@
1+package quicktype
2+
3+import io.circe.syntax._
4+import io.circe._
5+import cats.syntax.functor._
6+
7+// If a union has a null in, then we'll need this too...
8+type NullValue = None.type
9+
10+case class TopLevel (
11+ val hashCodeValue : String,
12+ val noSuchMethod : String,
13+ val runtimeType : Long,
14+ val toStringValue : Boolean
15+)
16+
17+object TopLevel:
18+ given io.circe.derivation.Configuration =
19+ io.circe.derivation.Configuration.default.withTransformMemberNames(
20+ io.circe.derivation.renaming.replaceWith(
21+ "hashCodeValue" -> "hashCode",
22+ "toStringValue" -> "toString"
23+ )
24+ )
25+ given io.circe.Codec.AsObject[TopLevel] = io.circe.derivation.ConfiguredCodec.derived
Aswiftdefault / quicktype.swift+98 −0
@@ -0,0 +1,98 @@
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+
6+import Foundation
7+
8+// MARK: - TopLevel
9+struct TopLevel: Codable {
10+ let hashCode: String
11+ let noSuchMethod: String
12+ let runtimeType: Int
13+ let toString: Bool
14+
15+ enum CodingKeys: String, CodingKey {
16+ case hashCode = "hashCode"
17+ case noSuchMethod = "noSuchMethod"
18+ case runtimeType = "runtimeType"
19+ case toString = "toString"
20+ }
21+}
22+
23+// MARK: TopLevel convenience initializers and mutators
24+
25+extension TopLevel {
26+ init(data: Data) throws {
27+ self = try newJSONDecoder().decode(TopLevel.self, from: data)
28+ }
29+
30+ init(_ json: String, using encoding: String.Encoding = .utf8) throws {
31+ guard let data = json.data(using: encoding) else {
32+ throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
33+ }
34+ try self.init(data: data)
35+ }
36+
37+ init(fromURL url: URL) throws {
38+ try self.init(data: try Data(contentsOf: url))
39+ }
40+
41+ func with(
42+ hashCode: String? = nil,
43+ noSuchMethod: String? = nil,
44+ runtimeType: Int? = nil,
45+ toString: Bool? = nil
46+ ) -> TopLevel {
47+ return TopLevel(
48+ hashCode: hashCode ?? self.hashCode,
49+ noSuchMethod: noSuchMethod ?? self.noSuchMethod,
50+ runtimeType: runtimeType ?? self.runtimeType,
51+ toString: toString ?? self.toString
52+ )
53+ }
54+
55+ func jsonData() throws -> Data {
56+ return try newJSONEncoder().encode(self)
57+ }
58+
59+ func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
60+ return String(data: try self.jsonData(), encoding: encoding)
61+ }
62+}
63+
64+// MARK: - Helper functions for creating encoders and decoders
65+
66+func newJSONDecoder() -> JSONDecoder {
67+ let decoder = JSONDecoder()
68+ decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in
69+ let container = try decoder.singleValueContainer()
70+ let dateStr = try container.decode(String.self)
71+
72+ let formatter = DateFormatter()
73+ formatter.calendar = Calendar(identifier: .iso8601)
74+ formatter.locale = Locale(identifier: "en_US_POSIX")
75+ formatter.timeZone = TimeZone(secondsFromGMT: 0)
76+ formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
77+ if let date = formatter.date(from: dateStr) {
78+ return date
79+ }
80+ formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
81+ if let date = formatter.date(from: dateStr) {
82+ return date
83+ }
84+ throw DecodingError.typeMismatch(Date.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not decode date"))
85+ })
86+ return decoder
87+}
88+
89+func newJSONEncoder() -> JSONEncoder {
90+ let encoder = JSONEncoder()
91+ let formatter = DateFormatter()
92+ formatter.calendar = Calendar(identifier: .iso8601)
93+ formatter.locale = Locale(identifier: "en_US_POSIX")
94+ formatter.timeZone = TimeZone(secondsFromGMT: 0)
95+ formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXXXX"
96+ encoder.dateEncodingStrategy = .formatted(formatter)
97+ return encoder
98+}
Atypescript-effect-schemadefault / TopLevel.ts+9 −0
@@ -0,0 +1,9 @@
1+import * as S from "effect/Schema";
2+
3+
4+export class TopLevel extends S.Class<TopLevel>("TopLevel")({
5+ "hashCode": S.String,
6+ "noSuchMethod": S.String,
7+ "runtimeType": S.Int,
8+ "toString": S.Boolean,
9+}) {}
Atypescript-zoddefault / TopLevel.ts+10 −0
@@ -0,0 +1,10 @@
1+import * as z from "zod";
2+
3+
4+export const TopLevelSchema = z.object({
5+ "hashCode": z.string(),
6+ "noSuchMethod": z.string(),
7+ "runtimeType": z.number().int(),
8+ "toString": z.boolean(),
9+});
10+export type TopLevel = z.infer<typeof TopLevelSchema>;
Atypescriptdefault / TopLevel.ts+210 −0
@@ -0,0 +1,210 @@
1+// To parse this data:
2+//
3+// import { Convert, TopLevel } from "./TopLevel";
4+//
5+// const topLevel = Convert.toTopLevel(json);
6+//
7+// These functions will throw an error if the JSON doesn't
8+// match the expected interface, even if the JSON is valid.
9+
10+export interface TopLevel {
11+ hashCode: string;
12+ noSuchMethod: string;
13+ runtimeType: number;
14+ toString: boolean;
15+}
16+
17+// Converts JSON strings to/from your types
18+// and asserts the results of JSON.parse at runtime
19+export class Convert {
20+ public static toTopLevel(json: string): TopLevel {
21+ return cast(JSON.parse(json), r("TopLevel"));
22+ }
23+
24+ public static topLevelToJson(value: TopLevel): string {
25+ return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
26+ }
27+}
28+
29+function invalidValue(typ: any, val: any, key: any, parent: any = ''): never {
30+ const prettyTyp = prettyTypeName(typ);
31+ const parentText = parent ? ` on ${parent}` : '';
32+ const keyText = key ? ` for key "${key}"` : '';
33+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
34+}
35+
36+function prettyTypeName(typ: any): string {
37+ if (Array.isArray(typ)) {
38+ if (typ.length === 2 && typ[0] === undefined) {
39+ return `an optional ${prettyTypeName(typ[1])}`;
40+ } else {
41+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
42+ }
43+ } else if (typeof typ === "object" && typ.literal !== undefined) {
44+ return typ.literal;
45+ } else {
46+ return typeof typ;
47+ }
48+}
49+
50+function jsonToJSProps(typ: any): any {
51+ if (typ.jsonToJS === undefined) {
52+ const map: any = {};
53+ typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
54+ typ.jsonToJS = map;
55+ }
56+ return typ.jsonToJS;
57+}
58+
59+function jsToJSONProps(typ: any): any {
60+ if (typ.jsToJSON === undefined) {
61+ const map: any = {};
62+ typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
63+ typ.jsToJSON = map;
64+ }
65+ return typ.jsToJSON;
66+}
67+
68+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
69+ function transformPrimitive(typ: string, val: any): any {
70+ if (typeof typ === typeof val) return val;
71+ return invalidValue(typ, val, key, parent);
72+ }
73+
74+ function transformUnion(typs: any[], val: any): any {
75+ // val must validate against one typ in typs
76+ const l = typs.length;
77+ for (let i = 0; i < l; i++) {
78+ const typ = typs[i];
79+ try {
80+ return transform(val, typ, getProps);
81+ } catch (_) {}
82+ }
83+ return invalidValue(typs, val, key, parent);
84+ }
85+
86+ function transformEnum(cases: string[], val: any): any {
87+ if (cases.indexOf(val) !== -1) return val;
88+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
89+ }
90+
91+ function transformArray(typ: any, val: any): any {
92+ // val must be an array with no invalid elements
93+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
94+
95+ return val.map(el => transform(el, typ, getProps));
96+ }
97+
98+ function transformDate(val: any): any {
99+ if (val === null) {
100+ return null;
101+ }
102+ const d = new Date(val);
103+ if (isNaN(d.valueOf())) {
104+ return invalidValue(l("Date"), val, key, parent);
105+ }
106+ return d;
107+ }
108+
109+ function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
110+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
111+ return invalidValue(l(ref || "object"), val, key, parent);
112+ }
113+ const result: any = {};
114+ Object.getOwnPropertyNames(props).forEach(key => {
115+ const prop = props[key];
116+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
117+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
118+ });
119+ Object.getOwnPropertyNames(val).forEach(key => {
120+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
121+ result[key] = transform(val[key], additional, getProps, key, ref);
122+ }
123+ });
124+ return result;
125+ }
126+
127+ if (typ === "any") return val;
128+ if (typ === null) {
129+ if (val === null) return val;
130+ return invalidValue(typ, val, key, parent);
131+ }
132+ if (typ === false) return invalidValue(typ, val, key, parent);
133+ let ref: any = undefined;
134+ while (typeof typ === "object" && typ.ref !== undefined) {
135+ ref = typ.ref;
136+ typ = typeMap[typ.ref];
137+ }
138+ if (Array.isArray(typ)) return transformEnum(typ, val);
139+ if (typeof typ === "object") {
140+ return typ.hasOwnProperty("pattern") ? typeof val === "string" && new RegExp(typ.pattern).test(val) ? val : invalidValue(typ, val, key, parent)
141+ : typ.hasOwnProperty("string") ? typeof val === "string" && (typ.min === undefined || val.length >= typ.min) && (typ.max === undefined || val.length <= typ.max) ? transform(val, typ.string, getProps, key, parent) : invalidValue(typ, val, key, parent)
142+ : typ.hasOwnProperty("number") ? typeof val === "number" && (typ.min === undefined || val >= typ.min) && (typ.max === undefined || val <= typ.max) ? transform(val, typ.number, getProps, key, parent) : invalidValue(typ, val, key, parent)
143+ : typ.hasOwnProperty("integer") ? typeof val === "number" && val % 1 === 0 ? val : invalidValue(l("integer"), val, key, parent)
144+ : typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
145+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
146+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
147+ : invalidValue(typ, val, key, parent);
148+ }
149+ // Numbers can be parsed by Date but shouldn't be.
150+ if (typ === Date && typeof val !== "number") return transformDate(val);
151+ return transformPrimitive(typ, val);
152+}
153+
154+function cast<T>(val: any, typ: any): T {
155+ return transform(val, typ, jsonToJSProps);
156+}
157+
158+function uncast<T>(val: T, typ: any): any {
159+ return transform(val, typ, jsToJSONProps);
160+}
161+
162+function l(typ: any) {
163+ return { literal: typ };
164+}
165+
166+function a(typ: any) {
167+ return { arrayItems: typ };
168+}
169+
170+function i(typ: any) {
171+ return { integer: typ };
172+}
173+
174+function p(pattern: any) {
175+ return { pattern };
176+}
177+
178+function s(typ: any, min: any, max: any) {
179+ return { string: typ, min, max };
180+}
181+
182+function n(typ: any, min: any, max: any) {
183+ return { number: typ, min, max };
184+}
185+
186+function u(...typs: any[]) {
187+ return { unionMembers: typs };
188+}
189+
190+function o(props: any[], additional: any) {
191+ return { props, additional };
192+}
193+
194+function m(additional: any) {
195+ const props: any[] = [];
196+ return { props, additional };
197+}
198+
199+function r(name: string) {
200+ return { ref: name };
201+}
202+
203+const typeMap: any = {
204+ "TopLevel": o([
205+ { json: "hashCode", js: "hashCode", typ: "" },
206+ { json: "noSuchMethod", js: "noSuchMethod", typ: "" },
207+ { json: "runtimeType", js: "runtimeType", typ: i(0) },
208+ { json: "toString", js: "toString", typ: true },
209+ ], false),
210+};
No generated files match these filters.