diff --git a/head/schema-cjson/test/inputs/schema/anyof-object-union.schema/default/TopLevel.c b/head/schema-cjson/test/inputs/schema/anyof-object-union.schema/default/TopLevel.c
new file mode 100644
index 0000000..9f5c8b3
--- /dev/null
+++ b/head/schema-cjson/test/inputs/schema/anyof-object-union.schema/default/TopLevel.c
@@ -0,0 +1,407 @@
+/**
+ * TopLevel.c
+ * This file has been autogenerated using quicktype https://github.com/quicktype/quicktype - DO NOT EDIT
+ */
+
+#include "TopLevel.h"
+
+struct SecondProperty * cJSON_GetSecondPropertyValue(const cJSON * j) {
+    struct SecondProperty * x = cJSON_malloc(sizeof(struct SecondProperty));
+    if (NULL != x) {
+        memset(x, 0, sizeof(struct SecondProperty));
+        if (cJSON_IsArray(j)) {
+            x->type = cJSON_Array;
+            list_t * x1 = list_create(false, NULL);
+            if (NULL != x1) {
+                cJSON * e1 = NULL;
+                cJSON_ArrayForEach(e1, j) {
+                    list_add_tail(x1, cJSON_GetMyObjectAValue(e1), sizeof(struct MyObjectA *));
+                }
+                x->value.my_object_a_array = x1;
+            }
+        }
+        else if (cJSON_IsObject(j)) {
+            x->type = cJSON_Object;
+            x->value.my_object_b = cJSON_GetMyObjectBValue(j);
+        }
+    }
+    return x;
+}
+
+cJSON * cJSON_CreateSecondProperty(const struct SecondProperty * x) {
+    cJSON * j = NULL;
+    if (NULL != x) {
+        if (cJSON_Array == x->type) {
+            cJSON * j1 = cJSON_CreateArray();
+            if (NULL != j1) {
+                struct MyObjectA * x1 = list_get_head(x->value.my_object_a_array);
+                while (NULL != x1) {
+                    cJSON_AddItemToArray(j1, cJSON_CreateMyObjectA(x1));
+                    x1 = list_get_next(x->value.my_object_a_array);
+                }
+                j = j1;
+            }
+        }
+        else if (cJSON_Object == x->type) {
+            j = cJSON_CreateMyObjectB(x->value.my_object_b);
+        }
+    }
+    return j;
+}
+
+void cJSON_DeleteSecondProperty(struct SecondProperty * x) {
+    if (NULL != x) {
+        if (cJSON_Array == x->type) {
+            if (NULL != x->value.my_object_a_array) {
+                struct MyObjectA * x1 = list_get_head(x->value.my_object_a_array);
+                while (NULL != x1) {
+                    cJSON_DeleteMyObjectA(x1);
+                    x1 = list_get_next(x->value.my_object_a_array);
+                }
+                list_release(x->value.my_object_a_array);
+            }
+        }
+        else if (cJSON_Object == x->type) {
+            cJSON_DeleteMyObjectB(x->value.my_object_b);
+        }
+        cJSON_free(x);
+    }
+}
+
+struct MyObject * cJSON_ParseMyObject(const char * s) {
+    struct MyObject * x = NULL;
+    if (NULL != s) {
+        cJSON * j = cJSON_Parse(s);
+        if (NULL != j) {
+            x = cJSON_GetMyObjectValue(j);
+            cJSON_Delete(j);
+        }
+    }
+    return x;
+}
+
+struct MyObject * cJSON_GetMyObjectValue(const cJSON * j) {
+    struct MyObject * x = NULL;
+    if (NULL != j) {
+        if (NULL != (x = cJSON_malloc(sizeof(struct MyObject)))) {
+            memset(x, 0, sizeof(struct MyObject));
+            if (cJSON_HasObjectItem(j, "a")) {
+                x->a = strdup(cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(j, "a")));
+            }
+            if (cJSON_HasObjectItem(j, "b")) {
+                if (NULL != (x->b = cJSON_malloc(sizeof(double)))) {
+                    *x->b = cJSON_GetNumberValue(cJSON_GetObjectItemCaseSensitive(j, "b"));
+                }
+            }
+            if (cJSON_HasObjectItem(j, "c")) {
+                if (NULL != (x->c = cJSON_malloc(sizeof(bool)))) {
+                    *x->c = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(j, "c"));
+                }
+            }
+            if (cJSON_HasObjectItem(j, "d")) {
+                x->d = strdup(cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(j, "d")));
+            }
+            if (cJSON_HasObjectItem(j, "e")) {
+                if (NULL != (x->e = cJSON_malloc(sizeof(double)))) {
+                    *x->e = cJSON_GetNumberValue(cJSON_GetObjectItemCaseSensitive(j, "e"));
+                }
+            }
+            if (cJSON_HasObjectItem(j, "f")) {
+                if (NULL != (x->f = cJSON_malloc(sizeof(bool)))) {
+                    *x->f = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(j, "f"));
+                }
+            }
+        }
+    }
+    return x;
+}
+
+cJSON * cJSON_CreateMyObject(const struct MyObject * x) {
+    cJSON * j = NULL;
+    if (NULL != x) {
+        if (NULL != (j = cJSON_CreateObject())) {
+            if (NULL != x->a) {
+                cJSON_AddStringToObject(j, "a", x->a);
+            }
+            if (NULL != x->b) {
+                cJSON_AddNumberToObject(j, "b", *x->b);
+            }
+            if (NULL != x->c) {
+                cJSON_AddBoolToObject(j, "c", *x->c);
+            }
+            if (NULL != x->d) {
+                cJSON_AddStringToObject(j, "d", x->d);
+            }
+            if (NULL != x->e) {
+                cJSON_AddNumberToObject(j, "e", *x->e);
+            }
+            if (NULL != x->f) {
+                cJSON_AddBoolToObject(j, "f", *x->f);
+            }
+        }
+    }
+    return j;
+}
+
+char * cJSON_PrintMyObject(const struct MyObject * x) {
+    char * s = NULL;
+    if (NULL != x) {
+        cJSON * j = cJSON_CreateMyObject(x);
+        if (NULL != j) {
+            s = cJSON_Print(j);
+            cJSON_Delete(j);
+        }
+    }
+    return s;
+}
+
+void cJSON_DeleteMyObject(struct MyObject * x) {
+    if (NULL != x) {
+        if (NULL != x->a) {
+            cJSON_free(x->a);
+        }
+        if (NULL != x->b) {
+            cJSON_free(x->b);
+        }
+        if (NULL != x->c) {
+            cJSON_free(x->c);
+        }
+        if (NULL != x->d) {
+            cJSON_free(x->d);
+        }
+        if (NULL != x->e) {
+            cJSON_free(x->e);
+        }
+        if (NULL != x->f) {
+            cJSON_free(x->f);
+        }
+        cJSON_free(x);
+    }
+}
+
+struct MyObjectA * cJSON_ParseMyObjectA(const char * s) {
+    struct MyObjectA * x = NULL;
+    if (NULL != s) {
+        cJSON * j = cJSON_Parse(s);
+        if (NULL != j) {
+            x = cJSON_GetMyObjectAValue(j);
+            cJSON_Delete(j);
+        }
+    }
+    return x;
+}
+
+struct MyObjectA * cJSON_GetMyObjectAValue(const cJSON * j) {
+    struct MyObjectA * x = NULL;
+    if (NULL != j) {
+        if (NULL != (x = cJSON_malloc(sizeof(struct MyObjectA)))) {
+            memset(x, 0, sizeof(struct MyObjectA));
+            if (cJSON_HasObjectItem(j, "a")) {
+                x->a = strdup(cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(j, "a")));
+            }
+            if (cJSON_HasObjectItem(j, "b")) {
+                if (NULL != (x->b = cJSON_malloc(sizeof(double)))) {
+                    *x->b = cJSON_GetNumberValue(cJSON_GetObjectItemCaseSensitive(j, "b"));
+                }
+            }
+            if (cJSON_HasObjectItem(j, "c")) {
+                if (NULL != (x->c = cJSON_malloc(sizeof(bool)))) {
+                    *x->c = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(j, "c"));
+                }
+            }
+        }
+    }
+    return x;
+}
+
+cJSON * cJSON_CreateMyObjectA(const struct MyObjectA * x) {
+    cJSON * j = NULL;
+    if (NULL != x) {
+        if (NULL != (j = cJSON_CreateObject())) {
+            if (NULL != x->a) {
+                cJSON_AddStringToObject(j, "a", x->a);
+            }
+            if (NULL != x->b) {
+                cJSON_AddNumberToObject(j, "b", *x->b);
+            }
+            if (NULL != x->c) {
+                cJSON_AddBoolToObject(j, "c", *x->c);
+            }
+        }
+    }
+    return j;
+}
+
+char * cJSON_PrintMyObjectA(const struct MyObjectA * x) {
+    char * s = NULL;
+    if (NULL != x) {
+        cJSON * j = cJSON_CreateMyObjectA(x);
+        if (NULL != j) {
+            s = cJSON_Print(j);
+            cJSON_Delete(j);
+        }
+    }
+    return s;
+}
+
+void cJSON_DeleteMyObjectA(struct MyObjectA * x) {
+    if (NULL != x) {
+        if (NULL != x->a) {
+            cJSON_free(x->a);
+        }
+        if (NULL != x->b) {
+            cJSON_free(x->b);
+        }
+        if (NULL != x->c) {
+            cJSON_free(x->c);
+        }
+        cJSON_free(x);
+    }
+}
+
+struct MyObjectB * cJSON_ParseMyObjectB(const char * s) {
+    struct MyObjectB * x = NULL;
+    if (NULL != s) {
+        cJSON * j = cJSON_Parse(s);
+        if (NULL != j) {
+            x = cJSON_GetMyObjectBValue(j);
+            cJSON_Delete(j);
+        }
+    }
+    return x;
+}
+
+struct MyObjectB * cJSON_GetMyObjectBValue(const cJSON * j) {
+    struct MyObjectB * x = NULL;
+    if (NULL != j) {
+        if (NULL != (x = cJSON_malloc(sizeof(struct MyObjectB)))) {
+            memset(x, 0, sizeof(struct MyObjectB));
+            if (cJSON_HasObjectItem(j, "d")) {
+                x->d = strdup(cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(j, "d")));
+            }
+            if (cJSON_HasObjectItem(j, "e")) {
+                if (NULL != (x->e = cJSON_malloc(sizeof(double)))) {
+                    *x->e = cJSON_GetNumberValue(cJSON_GetObjectItemCaseSensitive(j, "e"));
+                }
+            }
+            if (cJSON_HasObjectItem(j, "f")) {
+                if (NULL != (x->f = cJSON_malloc(sizeof(bool)))) {
+                    *x->f = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(j, "f"));
+                }
+            }
+        }
+    }
+    return x;
+}
+
+cJSON * cJSON_CreateMyObjectB(const struct MyObjectB * x) {
+    cJSON * j = NULL;
+    if (NULL != x) {
+        if (NULL != (j = cJSON_CreateObject())) {
+            if (NULL != x->d) {
+                cJSON_AddStringToObject(j, "d", x->d);
+            }
+            if (NULL != x->e) {
+                cJSON_AddNumberToObject(j, "e", *x->e);
+            }
+            if (NULL != x->f) {
+                cJSON_AddBoolToObject(j, "f", *x->f);
+            }
+        }
+    }
+    return j;
+}
+
+char * cJSON_PrintMyObjectB(const struct MyObjectB * x) {
+    char * s = NULL;
+    if (NULL != x) {
+        cJSON * j = cJSON_CreateMyObjectB(x);
+        if (NULL != j) {
+            s = cJSON_Print(j);
+            cJSON_Delete(j);
+        }
+    }
+    return s;
+}
+
+void cJSON_DeleteMyObjectB(struct MyObjectB * x) {
+    if (NULL != x) {
+        if (NULL != x->d) {
+            cJSON_free(x->d);
+        }
+        if (NULL != x->e) {
+            cJSON_free(x->e);
+        }
+        if (NULL != x->f) {
+            cJSON_free(x->f);
+        }
+        cJSON_free(x);
+    }
+}
+
+struct TopLevel * cJSON_ParseTopLevel(const char * s) {
+    struct TopLevel * x = NULL;
+    if (NULL != s) {
+        cJSON * j = cJSON_Parse(s);
+        if (NULL != j) {
+            x = cJSON_GetTopLevelValue(j);
+            cJSON_Delete(j);
+        }
+    }
+    return x;
+}
+
+struct TopLevel * cJSON_GetTopLevelValue(const cJSON * j) {
+    struct TopLevel * x = NULL;
+    if (NULL != j) {
+        if (NULL != (x = cJSON_malloc(sizeof(struct TopLevel)))) {
+            memset(x, 0, sizeof(struct TopLevel));
+            if (cJSON_HasObjectItem(j, "firstProperty")) {
+                x->first_property = cJSON_GetMyObjectValue(cJSON_GetObjectItemCaseSensitive(j, "firstProperty"));
+            }
+            if (cJSON_HasObjectItem(j, "secondProperty")) {
+                x->second_property = cJSON_GetSecondPropertyValue(cJSON_GetObjectItemCaseSensitive(j, "secondProperty"));
+            }
+        }
+    }
+    return x;
+}
+
+cJSON * cJSON_CreateTopLevel(const struct TopLevel * x) {
+    cJSON * j = NULL;
+    if (NULL != x) {
+        if (NULL != (j = cJSON_CreateObject())) {
+            if (NULL != x->first_property) {
+                cJSON_AddItemToObject(j, "firstProperty", cJSON_CreateMyObject(x->first_property));
+            }
+            if (NULL != x->second_property) {
+                cJSON_AddItemToObject(j, "secondProperty", cJSON_CreateSecondProperty(x->second_property));
+            }
+        }
+    }
+    return j;
+}
+
+char * cJSON_PrintTopLevel(const struct TopLevel * x) {
+    char * s = NULL;
+    if (NULL != x) {
+        cJSON * j = cJSON_CreateTopLevel(x);
+        if (NULL != j) {
+            s = cJSON_Print(j);
+            cJSON_Delete(j);
+        }
+    }
+    return s;
+}
+
+void cJSON_DeleteTopLevel(struct TopLevel * x) {
+    if (NULL != x) {
+        if (NULL != x->first_property) {
+            cJSON_DeleteMyObject(x->first_property);
+        }
+        if (NULL != x->second_property) {
+            cJSON_DeleteSecondProperty(x->second_property);
+        }
+        cJSON_free(x);
+    }
+}
diff --git a/head/schema-cjson/test/inputs/schema/anyof-object-union.schema/default/TopLevel.h b/head/schema-cjson/test/inputs/schema/anyof-object-union.schema/default/TopLevel.h
new file mode 100644
index 0000000..366c27d
--- /dev/null
+++ b/head/schema-cjson/test/inputs/schema/anyof-object-union.schema/default/TopLevel.h
@@ -0,0 +1,103 @@
+/**
+ * TopLevel.h
+ * This file has been autogenerated using quicktype https://github.com/quicktype/quicktype - DO NOT EDIT
+ * This file depends of https://github.com/DaveGamble/cJSON, https://github.com/joelguittet/c-list and https://github.com/joelguittet/c-hashtable
+ * To parse json data from json string use the following: struct <type> * data = cJSON_Parse<type>(<string>);
+ * To get json data from cJSON object use the following: struct <type> * data = cJSON_Get<type>Value(<cjson>);
+ * To get cJSON object from json data use the following: cJSON * cjson = cJSON_Create<type>(<data>);
+ * To print json string from json data use the following: char * string = cJSON_Print<type>(<data>);
+ * To delete json data use the following: cJSON_Delete<type>(<data>);
+ */
+
+#ifndef __TOPLEVEL_H__
+#define __TOPLEVEL_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <string.h>
+#include <cJSON.h>
+#include <hashtable.h>
+#include <list.h>
+
+#ifndef cJSON_Bool
+#define cJSON_Bool (cJSON_True | cJSON_False)
+#endif
+#ifndef cJSON_Map
+#define cJSON_Map (1 << 16)
+#endif
+#ifndef cJSON_Enum
+#define cJSON_Enum (1 << 17)
+#endif
+
+struct MyObject {
+    char * a;
+    double * b;
+    bool * c;
+    char * d;
+    double * e;
+    bool * f;
+};
+
+struct MyObjectA {
+    char * a;
+    double * b;
+    bool * c;
+};
+
+struct MyObjectB {
+    char * d;
+    double * e;
+    bool * f;
+};
+
+struct SecondProperty {
+    int type;
+    union {
+        list_t * my_object_a_array;
+        struct MyObjectB * my_object_b;
+    } value;
+};
+
+struct TopLevel {
+    struct MyObject * first_property;
+    struct SecondProperty * second_property;
+};
+
+struct SecondProperty * cJSON_GetSecondPropertyValue(const cJSON * j);
+cJSON * cJSON_CreateSecondProperty(const struct SecondProperty * x);
+void cJSON_DeleteSecondProperty(struct SecondProperty * x);
+
+struct MyObject * cJSON_ParseMyObject(const char * s);
+struct MyObject * cJSON_GetMyObjectValue(const cJSON * j);
+cJSON * cJSON_CreateMyObject(const struct MyObject * x);
+char * cJSON_PrintMyObject(const struct MyObject * x);
+void cJSON_DeleteMyObject(struct MyObject * x);
+
+struct MyObjectA * cJSON_ParseMyObjectA(const char * s);
+struct MyObjectA * cJSON_GetMyObjectAValue(const cJSON * j);
+cJSON * cJSON_CreateMyObjectA(const struct MyObjectA * x);
+char * cJSON_PrintMyObjectA(const struct MyObjectA * x);
+void cJSON_DeleteMyObjectA(struct MyObjectA * x);
+
+struct MyObjectB * cJSON_ParseMyObjectB(const char * s);
+struct MyObjectB * cJSON_GetMyObjectBValue(const cJSON * j);
+cJSON * cJSON_CreateMyObjectB(const struct MyObjectB * x);
+char * cJSON_PrintMyObjectB(const struct MyObjectB * x);
+void cJSON_DeleteMyObjectB(struct MyObjectB * x);
+
+struct TopLevel * cJSON_ParseTopLevel(const char * s);
+struct TopLevel * cJSON_GetTopLevelValue(const cJSON * j);
+cJSON * cJSON_CreateTopLevel(const struct TopLevel * x);
+char * cJSON_PrintTopLevel(const struct TopLevel * x);
+void cJSON_DeleteTopLevel(struct TopLevel * x);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __TOPLEVEL_H__ */
diff --git a/head/schema-cplusplus/test/inputs/schema/anyof-object-union.schema/default/quicktype.hpp b/head/schema-cplusplus/test/inputs/schema/anyof-object-union.schema/default/quicktype.hpp
new file mode 100644
index 0000000..03bcbe9
--- /dev/null
+++ b/head/schema-cplusplus/test/inputs/schema/anyof-object-union.schema/default/quicktype.hpp
@@ -0,0 +1,298 @@
+//  To parse this JSON data, first install
+//
+//      json.hpp  https://github.com/nlohmann/json
+//
+//  Then include this file, and then do
+//
+//     TopLevel data = nlohmann::json::parse(jsonString);
+
+#pragma once
+
+#include <optional>
+#include <variant>
+#include "json.hpp"
+
+#include <optional>
+#include <stdexcept>
+#include <regex>
+
+#ifndef NLOHMANN_OPT_HELPER
+#define NLOHMANN_OPT_HELPER
+namespace nlohmann {
+    template <typename T>
+    struct adl_serializer<std::shared_ptr<T>> {
+        static void to_json(json & j, const std::shared_ptr<T> & opt) {
+            if (!opt) j = nullptr; else j = *opt;
+        }
+
+        static std::shared_ptr<T> from_json(const json & j) {
+            if (j.is_null()) return std::shared_ptr<T>(); else return std::make_shared<T>(j.get<T>());
+        }
+    };
+    template <typename T>
+    struct adl_serializer<std::optional<T>> {
+        static void to_json(json & j, const std::optional<T> & opt) {
+            if (!opt) j = nullptr; else j = *opt;
+        }
+
+        static std::optional<T> from_json(const json & j) {
+            if (j.is_null()) return std::optional<T>(); else return std::make_optional<T>(j.get<T>());
+        }
+    };
+}
+#endif
+
+namespace quicktype {
+    using nlohmann::json;
+
+    #ifndef NLOHMANN_UNTYPED_quicktype_HELPER
+    #define NLOHMANN_UNTYPED_quicktype_HELPER
+    inline json get_untyped(const json & j, const char * property) {
+        if (j.find(property) != j.end()) {
+            return j.at(property).get<json>();
+        }
+        return json();
+    }
+
+    inline json get_untyped(const json & j, std::string property) {
+        return get_untyped(j, property.data());
+    }
+    #endif
+
+    #ifndef NLOHMANN_OPTIONAL_quicktype_HELPER
+    #define NLOHMANN_OPTIONAL_quicktype_HELPER
+    template <typename T>
+    inline std::shared_ptr<T> get_heap_optional(const json & j, const char * property) {
+        auto it = j.find(property);
+        if (it != j.end() && !it->is_null()) {
+            return j.at(property).get<std::shared_ptr<T>>();
+        }
+        return std::shared_ptr<T>();
+    }
+
+    template <typename T>
+    inline std::shared_ptr<T> get_heap_optional(const json & j, std::string property) {
+        return get_heap_optional<T>(j, property.data());
+    }
+    template <typename T>
+    inline std::optional<T> get_stack_optional(const json & j, const char * property) {
+        auto it = j.find(property);
+        if (it != j.end() && !it->is_null()) {
+            return j.at(property).get<std::optional<T>>();
+        }
+        return std::optional<T>();
+    }
+
+    template <typename T>
+    inline std::optional<T> get_stack_optional(const json & j, std::string property) {
+        return get_stack_optional<T>(j, property.data());
+    }
+    #endif
+
+    class MyObject {
+        public:
+        MyObject() = default;
+        virtual ~MyObject() = default;
+
+        private:
+        std::optional<std::string> a;
+        std::optional<double> b;
+        std::optional<bool> c;
+        std::optional<std::string> d;
+        std::optional<double> e;
+        std::optional<bool> f;
+
+        public:
+        const std::optional<std::string> & get_a() const { return a; }
+        std::optional<std::string> & get_mutable_a() { return a; }
+        void set_a(const std::optional<std::string> & value) { this->a = value; }
+
+        const std::optional<double> & get_b() const { return b; }
+        std::optional<double> & get_mutable_b() { return b; }
+        void set_b(const std::optional<double> & value) { this->b = value; }
+
+        const std::optional<bool> & get_c() const { return c; }
+        std::optional<bool> & get_mutable_c() { return c; }
+        void set_c(const std::optional<bool> & value) { this->c = value; }
+
+        const std::optional<std::string> & get_d() const { return d; }
+        std::optional<std::string> & get_mutable_d() { return d; }
+        void set_d(const std::optional<std::string> & value) { this->d = value; }
+
+        const std::optional<double> & get_e() const { return e; }
+        std::optional<double> & get_mutable_e() { return e; }
+        void set_e(const std::optional<double> & value) { this->e = value; }
+
+        const std::optional<bool> & get_f() const { return f; }
+        std::optional<bool> & get_mutable_f() { return f; }
+        void set_f(const std::optional<bool> & value) { this->f = value; }
+    };
+
+    class MyObjectA {
+        public:
+        MyObjectA() = default;
+        virtual ~MyObjectA() = default;
+
+        private:
+        std::optional<std::string> a;
+        std::optional<double> b;
+        std::optional<bool> c;
+
+        public:
+        const std::optional<std::string> & get_a() const { return a; }
+        std::optional<std::string> & get_mutable_a() { return a; }
+        void set_a(const std::optional<std::string> & value) { this->a = value; }
+
+        const std::optional<double> & get_b() const { return b; }
+        std::optional<double> & get_mutable_b() { return b; }
+        void set_b(const std::optional<double> & value) { this->b = value; }
+
+        const std::optional<bool> & get_c() const { return c; }
+        std::optional<bool> & get_mutable_c() { return c; }
+        void set_c(const std::optional<bool> & value) { this->c = value; }
+    };
+
+    class MyObjectB {
+        public:
+        MyObjectB() = default;
+        virtual ~MyObjectB() = default;
+
+        private:
+        std::optional<std::string> d;
+        std::optional<double> e;
+        std::optional<bool> f;
+
+        public:
+        const std::optional<std::string> & get_d() const { return d; }
+        std::optional<std::string> & get_mutable_d() { return d; }
+        void set_d(const std::optional<std::string> & value) { this->d = value; }
+
+        const std::optional<double> & get_e() const { return e; }
+        std::optional<double> & get_mutable_e() { return e; }
+        void set_e(const std::optional<double> & value) { this->e = value; }
+
+        const std::optional<bool> & get_f() const { return f; }
+        std::optional<bool> & get_mutable_f() { return f; }
+        void set_f(const std::optional<bool> & value) { this->f = value; }
+    };
+
+    using SecondProperty = std::variant<std::vector<MyObjectA>, MyObjectB>;
+
+    class TopLevel {
+        public:
+        TopLevel() = default;
+        virtual ~TopLevel() = default;
+
+        private:
+        std::optional<MyObject> first_property;
+        std::optional<SecondProperty> second_property;
+
+        public:
+        const std::optional<MyObject> & get_first_property() const { return first_property; }
+        std::optional<MyObject> & get_mutable_first_property() { return first_property; }
+        void set_first_property(const std::optional<MyObject> & value) { this->first_property = value; }
+
+        const std::optional<SecondProperty> & get_second_property() const { return second_property; }
+        std::optional<SecondProperty> & get_mutable_second_property() { return second_property; }
+        void set_second_property(const std::optional<SecondProperty> & value) { this->second_property = value; }
+    };
+}
+
+namespace quicktype {
+void from_json(const json & j, MyObject & x);
+void to_json(json & j, const MyObject & x);
+
+void from_json(const json & j, MyObjectA & x);
+void to_json(json & j, const MyObjectA & x);
+
+void from_json(const json & j, MyObjectB & x);
+void to_json(json & j, const MyObjectB & x);
+
+void from_json(const json & j, TopLevel & x);
+void to_json(json & j, const TopLevel & x);
+}
+namespace nlohmann {
+template <>
+struct adl_serializer<std::variant<std::vector<quicktype::MyObjectA>, quicktype::MyObjectB>> {
+    static void from_json(const json & j, std::variant<std::vector<quicktype::MyObjectA>, quicktype::MyObjectB> & x);
+    static void to_json(json & j, const std::variant<std::vector<quicktype::MyObjectA>, quicktype::MyObjectB> & x);
+};
+}
+namespace quicktype {
+    inline void from_json(const json & j, MyObject& x) {
+        x.set_a(get_stack_optional<std::string>(j, "a"));
+        x.set_b(get_stack_optional<double>(j, "b"));
+        x.set_c(get_stack_optional<bool>(j, "c"));
+        x.set_d(get_stack_optional<std::string>(j, "d"));
+        x.set_e(get_stack_optional<double>(j, "e"));
+        x.set_f(get_stack_optional<bool>(j, "f"));
+    }
+
+    inline void to_json(json & j, const MyObject & x) {
+        j = json::object();
+        j["a"] = x.get_a();
+        j["b"] = x.get_b();
+        j["c"] = x.get_c();
+        j["d"] = x.get_d();
+        j["e"] = x.get_e();
+        j["f"] = x.get_f();
+    }
+
+    inline void from_json(const json & j, MyObjectA& x) {
+        x.set_a(get_stack_optional<std::string>(j, "a"));
+        x.set_b(get_stack_optional<double>(j, "b"));
+        x.set_c(get_stack_optional<bool>(j, "c"));
+    }
+
+    inline void to_json(json & j, const MyObjectA & x) {
+        j = json::object();
+        j["a"] = x.get_a();
+        j["b"] = x.get_b();
+        j["c"] = x.get_c();
+    }
+
+    inline void from_json(const json & j, MyObjectB& x) {
+        x.set_d(get_stack_optional<std::string>(j, "d"));
+        x.set_e(get_stack_optional<double>(j, "e"));
+        x.set_f(get_stack_optional<bool>(j, "f"));
+    }
+
+    inline void to_json(json & j, const MyObjectB & x) {
+        j = json::object();
+        j["d"] = x.get_d();
+        j["e"] = x.get_e();
+        j["f"] = x.get_f();
+    }
+
+    inline void from_json(const json & j, TopLevel& x) {
+        x.set_first_property(get_stack_optional<MyObject>(j, "firstProperty"));
+        x.set_second_property(get_stack_optional<std::variant<std::vector<MyObjectA>, MyObjectB>>(j, "secondProperty"));
+    }
+
+    inline void to_json(json & j, const TopLevel & x) {
+        j = json::object();
+        j["firstProperty"] = x.get_first_property();
+        j["secondProperty"] = x.get_second_property();
+    }
+}
+namespace nlohmann {
+    inline void adl_serializer<std::variant<std::vector<quicktype::MyObjectA>, quicktype::MyObjectB>>::from_json(const json & j, std::variant<std::vector<quicktype::MyObjectA>, quicktype::MyObjectB> & x) {
+        if (j.is_object())
+            x = j.get<quicktype::MyObjectB>();
+        else if (j.is_array())
+            x = j.get<std::vector<quicktype::MyObjectA>>();
+        else throw std::runtime_error("Could not deserialise!");
+    }
+
+    inline void adl_serializer<std::variant<std::vector<quicktype::MyObjectA>, quicktype::MyObjectB>>::to_json(json & j, const std::variant<std::vector<quicktype::MyObjectA>, quicktype::MyObjectB> & x) {
+        switch (x.index()) {
+            case 0:
+                j = std::get<std::vector<quicktype::MyObjectA>>(x);
+                break;
+            case 1:
+                j = std::get<quicktype::MyObjectB>(x);
+                break;
+            default: throw std::runtime_error("Input JSON does not conform to schema!");
+        }
+    }
+}
diff --git a/head/schema-csharp/test/inputs/schema/anyof-object-union.schema/default/QuickType.cs b/head/schema-csharp/test/inputs/schema/anyof-object-union.schema/default/QuickType.cs
new file mode 100644
index 0000000..7f4e3de
--- /dev/null
+++ b/head/schema-csharp/test/inputs/schema/anyof-object-union.schema/default/QuickType.cs
@@ -0,0 +1,156 @@
+// <auto-generated />
+//
+// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
+//
+//    using QuickType;
+//
+//    var topLevel = TopLevel.FromJson(jsonString);
+#nullable enable
+#pragma warning disable CS8618
+#pragma warning disable CS8601
+#pragma warning disable CS8602
+#pragma warning disable CS8603
+#pragma warning disable CS8604
+#pragma warning disable CS8625
+#pragma warning disable CS8765
+
+namespace QuickType
+{
+    using System;
+    using System.Collections.Generic;
+
+    using System.Globalization;
+    using Newtonsoft.Json;
+    using Newtonsoft.Json.Converters;
+
+    public partial class TopLevel
+    {
+        [JsonProperty("firstProperty", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public MyObject? FirstProperty { get; set; }
+
+        [JsonProperty("secondProperty", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public SecondProperty? SecondProperty { get; set; }
+    }
+
+    public partial class MyObject
+    {
+        [JsonProperty("a", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public string? A { get; set; }
+
+        [JsonProperty("b", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public double? B { get; set; }
+
+        [JsonProperty("c", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public bool? C { get; set; }
+
+        [JsonProperty("d", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public string? D { get; set; }
+
+        [JsonProperty("e", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public double? E { get; set; }
+
+        [JsonProperty("f", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public bool? F { get; set; }
+    }
+
+    public partial class MyObjectA
+    {
+        [JsonProperty("a", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public string? A { get; set; }
+
+        [JsonProperty("b", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public double? B { get; set; }
+
+        [JsonProperty("c", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public bool? C { get; set; }
+    }
+
+    public partial class MyObjectB
+    {
+        [JsonProperty("d", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public string? D { get; set; }
+
+        [JsonProperty("e", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public double? E { get; set; }
+
+        [JsonProperty("f", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public bool? F { get; set; }
+    }
+
+    public partial struct SecondProperty
+    {
+        public MyObjectA[]? MyObjectAArray;
+        public MyObjectB? MyObjectB;
+
+        public static implicit operator SecondProperty(MyObjectA[] MyObjectAArray) => new SecondProperty { MyObjectAArray = MyObjectAArray };
+        public static implicit operator SecondProperty(MyObjectB MyObjectB) => new SecondProperty { MyObjectB = MyObjectB };
+    }
+
+    public partial class TopLevel
+    {
+        public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings);
+    }
+
+    public static partial class Serialize
+    {
+        public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
+    }
+
+    internal static partial class Converter
+    {
+        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
+        {
+            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
+            DateParseHandling = DateParseHandling.None,
+            Converters =
+            {
+                SecondPropertyConverter.Singleton,
+                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
+            },
+        };
+    }
+
+    internal class SecondPropertyConverter : JsonConverter
+    {
+        public override bool CanConvert(Type t) => t == typeof(SecondProperty) || t == typeof(SecondProperty?);
+
+        public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
+        {
+            switch (reader.TokenType)
+            {
+                case JsonToken.StartObject:
+                    var objectValue = serializer.Deserialize<MyObjectB>(reader);
+                    return new SecondProperty { MyObjectB = objectValue };
+                case JsonToken.StartArray:
+                    var arrayValue = serializer.Deserialize<MyObjectA[]>(reader);
+                    return new SecondProperty { MyObjectAArray = arrayValue };
+            }
+            throw new Exception("Cannot unmarshal type SecondProperty");
+        }
+
+        public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
+        {
+            var value = (SecondProperty)untypedValue;
+            if (value.MyObjectAArray != null)
+            {
+                serializer.Serialize(writer, value.MyObjectAArray);
+                return;
+            }
+            if (value.MyObjectB != null)
+            {
+                serializer.Serialize(writer, value.MyObjectB);
+                return;
+            }
+            throw new Exception("Cannot marshal type SecondProperty");
+        }
+
+        public static readonly SecondPropertyConverter Singleton = new SecondPropertyConverter();
+    }
+}
+#pragma warning restore CS8618
+#pragma warning restore CS8601
+#pragma warning restore CS8602
+#pragma warning restore CS8603
+#pragma warning restore CS8604
+#pragma warning restore CS8625
+#pragma warning restore CS8765
diff --git a/head/schema-csharp-SystemTextJson/test/inputs/schema/anyof-object-union.schema/default/QuickType.cs b/head/schema-csharp-SystemTextJson/test/inputs/schema/anyof-object-union.schema/default/QuickType.cs
new file mode 100644
index 0000000..45ef272
--- /dev/null
+++ b/head/schema-csharp-SystemTextJson/test/inputs/schema/anyof-object-union.schema/default/QuickType.cs
@@ -0,0 +1,273 @@
+// <auto-generated />
+//
+// To parse this JSON data, add NuGet 'System.Text.Json' then do:
+//
+//    using QuickType;
+//
+//    var topLevel = TopLevel.FromJson(jsonString);
+#nullable enable
+#pragma warning disable CS8618
+#pragma warning disable CS8601
+#pragma warning disable CS8602
+#pragma warning disable CS8603
+
+namespace QuickType
+{
+    using System;
+    using System.Collections.Generic;
+
+    using System.Text.Json;
+    using System.Text.Json.Serialization;
+    using System.Globalization;
+
+    public partial class TopLevel
+    {
+        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+        [JsonPropertyName("firstProperty")]
+        public MyObject? FirstProperty { get; set; }
+
+        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+        [JsonPropertyName("secondProperty")]
+        public SecondProperty? SecondProperty { get; set; }
+    }
+
+    public partial class MyObject
+    {
+        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+        [JsonPropertyName("a")]
+        public string? A { get; set; }
+
+        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+        [JsonPropertyName("b")]
+        public double? B { get; set; }
+
+        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+        [JsonPropertyName("c")]
+        public bool? C { get; set; }
+
+        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+        [JsonPropertyName("d")]
+        public string? D { get; set; }
+
+        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+        [JsonPropertyName("e")]
+        public double? E { get; set; }
+
+        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+        [JsonPropertyName("f")]
+        public bool? F { get; set; }
+    }
+
+    public partial class MyObjectA
+    {
+        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+        [JsonPropertyName("a")]
+        public string? A { get; set; }
+
+        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+        [JsonPropertyName("b")]
+        public double? B { get; set; }
+
+        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+        [JsonPropertyName("c")]
+        public bool? C { get; set; }
+    }
+
+    public partial class MyObjectB
+    {
+        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+        [JsonPropertyName("d")]
+        public string? D { get; set; }
+
+        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+        [JsonPropertyName("e")]
+        public double? E { get; set; }
+
+        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+        [JsonPropertyName("f")]
+        public bool? F { get; set; }
+    }
+
+    public partial struct SecondProperty
+    {
+        public MyObjectA[]? MyObjectAArray;
+        public MyObjectB? MyObjectB;
+
+        public static implicit operator SecondProperty(MyObjectA[] MyObjectAArray) => new SecondProperty { MyObjectAArray = MyObjectAArray };
+        public static implicit operator SecondProperty(MyObjectB MyObjectB) => new SecondProperty { MyObjectB = MyObjectB };
+    }
+
+    public partial class TopLevel
+    {
+        public static TopLevel FromJson(string json) => JsonSerializer.Deserialize<TopLevel>(json, QuickType.Converter.Settings);
+    }
+
+    public static partial class Serialize
+    {
+        public static string ToJson(this TopLevel self) => JsonSerializer.Serialize(self, QuickType.Converter.Settings);
+    }
+
+    internal static partial class Converter
+    {
+        public static readonly JsonSerializerOptions Settings = new(JsonSerializerDefaults.General)
+        {
+            Converters =
+            {
+                SecondPropertyConverter.Singleton,
+                new DateOnlyConverter(),
+                new TimeOnlyConverter(),
+                IsoDateTimeOffsetConverter.Singleton
+            },
+        };
+    }
+
+    internal class SecondPropertyConverter : JsonConverter<SecondProperty>
+    {
+        public override bool CanConvert(Type t) => t == typeof(SecondProperty);
+
+        public override SecondProperty Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+        {
+            switch (reader.TokenType)
+            {
+                case JsonTokenType.StartObject:
+                    var objectValue = JsonSerializer.Deserialize<MyObjectB>(ref reader, options);
+                    return new SecondProperty { MyObjectB = objectValue };
+                case JsonTokenType.StartArray:
+                    var arrayValue = JsonSerializer.Deserialize<MyObjectA[]>(ref reader, options);
+                    return new SecondProperty { MyObjectAArray = arrayValue };
+            }
+            throw new JsonException("Cannot unmarshal type SecondProperty");
+        }
+
+        public override void Write(Utf8JsonWriter writer, SecondProperty value, JsonSerializerOptions options)
+        {
+            if (value.MyObjectAArray != null)
+            {
+                JsonSerializer.Serialize(writer, value.MyObjectAArray, options);
+                return;
+            }
+            if (value.MyObjectB != null)
+            {
+                JsonSerializer.Serialize(writer, value.MyObjectB, options);
+                return;
+            }
+            throw new NotSupportedException("Cannot marshal type SecondProperty");
+        }
+
+        public static readonly SecondPropertyConverter Singleton = new SecondPropertyConverter();
+    }
+    
+    public class DateOnlyConverter : JsonConverter<DateOnly>
+    {
+        private readonly string serializationFormat;
+        public DateOnlyConverter() : this(null) { }
+
+        public DateOnlyConverter(string? serializationFormat)
+        {
+                this.serializationFormat = serializationFormat ?? "yyyy-MM-dd";
+        }
+
+        public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+        {
+                var value = reader.GetString();
+                return DateOnly.Parse(value!);
+        }
+
+        public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
+                => writer.WriteStringValue(value.ToString(serializationFormat));
+    }
+
+    public class TimeOnlyConverter : JsonConverter<TimeOnly>
+    {
+        private readonly string serializationFormat;
+
+        public TimeOnlyConverter() : this(null) { }
+
+        public TimeOnlyConverter(string? serializationFormat)
+        {
+                this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff";
+        }
+
+        public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+        {
+                var value = reader.GetString();
+                return TimeOnly.Parse(value!);
+        }
+
+        public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options)
+                => writer.WriteStringValue(value.ToString(serializationFormat));
+    }
+
+    internal class IsoDateTimeOffsetConverter : JsonConverter<DateTimeOffset>
+    {
+        public override bool CanConvert(Type t) => t == typeof(DateTimeOffset);
+
+        private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
+
+        private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind;
+        private string? _dateTimeFormat;
+        private CultureInfo? _culture;
+
+        public DateTimeStyles DateTimeStyles
+        {
+                get => _dateTimeStyles;
+                set => _dateTimeStyles = value;
+        }
+
+        public string? DateTimeFormat
+        {
+                get => _dateTimeFormat ?? string.Empty;
+                set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value;
+        }
+
+        public CultureInfo Culture
+        {
+                get => _culture ?? CultureInfo.CurrentCulture;
+                set => _culture = value;
+        }
+
+        public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
+        {
+                string text;
+
+
+                if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
+                        || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
+                {
+                        value = value.ToUniversalTime();
+                }
+
+                text = value.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
+
+                writer.WriteStringValue(text);
+        }
+
+        public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+        {
+                string? dateText = reader.GetString();
+
+                if (string.IsNullOrEmpty(dateText) == false)
+                {
+                        if (!string.IsNullOrEmpty(_dateTimeFormat))
+                        {
+                                return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
+                        }
+                        else
+                        {
+                                return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles);
+                        }
+                }
+                else
+                {
+                        return default(DateTimeOffset);
+                }
+        }
+
+
+        public static readonly IsoDateTimeOffsetConverter Singleton = new IsoDateTimeOffsetConverter();
+    }
+}
+#pragma warning restore CS8618
+#pragma warning restore CS8601
+#pragma warning restore CS8602
+#pragma warning restore CS8603
diff --git a/head/schema-csharp-records/test/inputs/schema/anyof-object-union.schema/default/QuickType.cs b/head/schema-csharp-records/test/inputs/schema/anyof-object-union.schema/default/QuickType.cs
new file mode 100644
index 0000000..5abfd4a
--- /dev/null
+++ b/head/schema-csharp-records/test/inputs/schema/anyof-object-union.schema/default/QuickType.cs
@@ -0,0 +1,156 @@
+// <auto-generated />
+//
+// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
+//
+//    using QuickType;
+//
+//    var topLevel = TopLevel.FromJson(jsonString);
+#nullable enable
+#pragma warning disable CS8618
+#pragma warning disable CS8601
+#pragma warning disable CS8602
+#pragma warning disable CS8603
+#pragma warning disable CS8604
+#pragma warning disable CS8625
+#pragma warning disable CS8765
+
+namespace QuickType
+{
+    using System;
+    using System.Collections.Generic;
+
+    using System.Globalization;
+    using Newtonsoft.Json;
+    using Newtonsoft.Json.Converters;
+
+    public partial record TopLevel
+    {
+        [JsonProperty("firstProperty", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public MyObject? FirstProperty { get; set; }
+
+        [JsonProperty("secondProperty", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public SecondProperty? SecondProperty { get; set; }
+    }
+
+    public partial record MyObject
+    {
+        [JsonProperty("a", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public string? A { get; set; }
+
+        [JsonProperty("b", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public double? B { get; set; }
+
+        [JsonProperty("c", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public bool? C { get; set; }
+
+        [JsonProperty("d", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public string? D { get; set; }
+
+        [JsonProperty("e", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public double? E { get; set; }
+
+        [JsonProperty("f", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public bool? F { get; set; }
+    }
+
+    public partial record MyObjectA
+    {
+        [JsonProperty("a", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public string? A { get; set; }
+
+        [JsonProperty("b", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public double? B { get; set; }
+
+        [JsonProperty("c", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public bool? C { get; set; }
+    }
+
+    public partial record MyObjectB
+    {
+        [JsonProperty("d", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public string? D { get; set; }
+
+        [JsonProperty("e", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public double? E { get; set; }
+
+        [JsonProperty("f", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public bool? F { get; set; }
+    }
+
+    public partial struct SecondProperty
+    {
+        public MyObjectA[]? MyObjectAArray;
+        public MyObjectB? MyObjectB;
+
+        public static implicit operator SecondProperty(MyObjectA[] MyObjectAArray) => new SecondProperty { MyObjectAArray = MyObjectAArray };
+        public static implicit operator SecondProperty(MyObjectB MyObjectB) => new SecondProperty { MyObjectB = MyObjectB };
+    }
+
+    public partial record TopLevel
+    {
+        public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings);
+    }
+
+    public static partial class Serialize
+    {
+        public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
+    }
+
+    internal static partial class Converter
+    {
+        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
+        {
+            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
+            DateParseHandling = DateParseHandling.None,
+            Converters =
+            {
+                SecondPropertyConverter.Singleton,
+                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
+            },
+        };
+    }
+
+    internal class SecondPropertyConverter : JsonConverter
+    {
+        public override bool CanConvert(Type t) => t == typeof(SecondProperty) || t == typeof(SecondProperty?);
+
+        public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
+        {
+            switch (reader.TokenType)
+            {
+                case JsonToken.StartObject:
+                    var objectValue = serializer.Deserialize<MyObjectB>(reader);
+                    return new SecondProperty { MyObjectB = objectValue };
+                case JsonToken.StartArray:
+                    var arrayValue = serializer.Deserialize<MyObjectA[]>(reader);
+                    return new SecondProperty { MyObjectAArray = arrayValue };
+            }
+            throw new Exception("Cannot unmarshal type SecondProperty");
+        }
+
+        public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
+        {
+            var value = (SecondProperty)untypedValue;
+            if (value.MyObjectAArray != null)
+            {
+                serializer.Serialize(writer, value.MyObjectAArray);
+                return;
+            }
+            if (value.MyObjectB != null)
+            {
+                serializer.Serialize(writer, value.MyObjectB);
+                return;
+            }
+            throw new Exception("Cannot marshal type SecondProperty");
+        }
+
+        public static readonly SecondPropertyConverter Singleton = new SecondPropertyConverter();
+    }
+}
+#pragma warning restore CS8618
+#pragma warning restore CS8601
+#pragma warning restore CS8602
+#pragma warning restore CS8603
+#pragma warning restore CS8604
+#pragma warning restore CS8625
+#pragma warning restore CS8765
diff --git a/head/schema-dart/test/inputs/schema/anyof-object-union.schema/default/TopLevel.dart b/head/schema-dart/test/inputs/schema/anyof-object-union.schema/default/TopLevel.dart
new file mode 100644
index 0000000..2174b2e
--- /dev/null
+++ b/head/schema-dart/test/inputs/schema/anyof-object-union.schema/default/TopLevel.dart
@@ -0,0 +1,113 @@
+// To parse this JSON data, do
+//
+//     final topLevel = topLevelFromJson(jsonString);
+
+import 'dart:convert';
+
+TopLevel topLevelFromJson(String str) => TopLevel.fromJson(json.decode(str));
+
+String topLevelToJson(TopLevel data) => json.encode(data.toJson());
+
+class TopLevel {
+    final MyObject? firstProperty;
+    final dynamic secondProperty;
+
+    TopLevel({
+        this.firstProperty,
+        this.secondProperty,
+    });
+
+    factory TopLevel.fromJson(Map<String, dynamic> json) => TopLevel(
+        firstProperty: json["firstProperty"] == null ? null : MyObject.fromJson(json["firstProperty"]),
+        secondProperty: json["secondProperty"],
+    );
+
+    Map<String, dynamic> toJson() => {
+        "firstProperty": firstProperty?.toJson(),
+        "secondProperty": secondProperty,
+    };
+}
+
+class MyObject {
+    final String? a;
+    final double? b;
+    final bool? c;
+    final String? d;
+    final double? e;
+    final bool? f;
+
+    MyObject({
+        this.a,
+        this.b,
+        this.c,
+        this.d,
+        this.e,
+        this.f,
+    });
+
+    factory MyObject.fromJson(Map<String, dynamic> json) => MyObject(
+        a: json["a"],
+        b: json["b"]?.toDouble(),
+        c: json["c"],
+        d: json["d"],
+        e: json["e"]?.toDouble(),
+        f: json["f"],
+    );
+
+    Map<String, dynamic> toJson() => {
+        "a": a,
+        "b": b,
+        "c": c,
+        "d": d,
+        "e": e,
+        "f": f,
+    };
+}
+
+class MyObjectA {
+    final String? a;
+    final double? b;
+    final bool? c;
+
+    MyObjectA({
+        this.a,
+        this.b,
+        this.c,
+    });
+
+    factory MyObjectA.fromJson(Map<String, dynamic> json) => MyObjectA(
+        a: json["a"],
+        b: json["b"]?.toDouble(),
+        c: json["c"],
+    );
+
+    Map<String, dynamic> toJson() => {
+        "a": a,
+        "b": b,
+        "c": c,
+    };
+}
+
+class MyObjectB {
+    final String? d;
+    final double? e;
+    final bool? f;
+
+    MyObjectB({
+        this.d,
+        this.e,
+        this.f,
+    });
+
+    factory MyObjectB.fromJson(Map<String, dynamic> json) => MyObjectB(
+        d: json["d"],
+        e: json["e"]?.toDouble(),
+        f: json["f"],
+    );
+
+    Map<String, dynamic> toJson() => {
+        "d": d,
+        "e": e,
+        "f": f,
+    };
+}
diff --git a/head/schema-elixir/test/inputs/schema/anyof-object-union.schema/default/QuickType.ex b/head/schema-elixir/test/inputs/schema/anyof-object-union.schema/default/QuickType.ex
new file mode 100644
index 0000000..79c56c2
--- /dev/null
+++ b/head/schema-elixir/test/inputs/schema/anyof-object-union.schema/default/QuickType.ex
@@ -0,0 +1,174 @@
+# This file was autogenerated using quicktype https://github.com/quicktype/quicktype
+#
+# Add Jason to your mix.exs
+#
+# Decode a JSON string: TopLevel.from_json(data)
+# Encode into a JSON string: TopLevel.to_json(struct)
+
+defmodule MyObject do
+  defstruct [:a, :b, :c, :d, :e, :f]
+
+  @type t :: %__MODULE__{
+          a: String.t() | nil,
+          b: float() | nil,
+          c: boolean() | nil,
+          d: String.t() | nil,
+          e: float() | nil,
+          f: boolean() | nil
+        }
+
+  def from_map(m) do
+    %MyObject{
+      a: m["a"],
+      b: m["b"],
+      c: m["c"],
+      d: m["d"],
+      e: m["e"],
+      f: m["f"],
+    }
+  end
+
+  def from_json(json) do
+    json
+          |> Jason.decode!()
+          |> from_map()
+  end
+
+  def to_map(struct) do
+    %{
+      "a" => struct.a,
+      "b" => struct.b,
+      "c" => struct.c,
+      "d" => struct.d,
+      "e" => struct.e,
+      "f" => struct.f,
+    }
+  end
+
+  def to_json(struct) do
+    struct
+          |> to_map()
+          |> Jason.encode!()
+  end
+end
+
+defmodule MyObjectA do
+  defstruct [:a, :b, :c]
+
+  @type t :: %__MODULE__{
+          a: String.t() | nil,
+          b: float() | nil,
+          c: boolean() | nil
+        }
+
+  def from_map(m) do
+    %MyObjectA{
+      a: m["a"],
+      b: m["b"],
+      c: m["c"],
+    }
+  end
+
+  def from_json(json) do
+    json
+          |> Jason.decode!()
+          |> from_map()
+  end
+
+  def to_map(struct) do
+    %{
+      "a" => struct.a,
+      "b" => struct.b,
+      "c" => struct.c,
+    }
+  end
+
+  def to_json(struct) do
+    struct
+          |> to_map()
+          |> Jason.encode!()
+  end
+end
+
+defmodule MyObjectB do
+  defstruct [:d, :e, :f]
+
+  @type t :: %__MODULE__{
+          d: String.t() | nil,
+          e: float() | nil,
+          f: boolean() | nil
+        }
+
+  def from_map(m) do
+    %MyObjectB{
+      d: m["d"],
+      e: m["e"],
+      f: m["f"],
+    }
+  end
+
+  def from_json(json) do
+    json
+          |> Jason.decode!()
+          |> from_map()
+  end
+
+  def to_map(struct) do
+    %{
+      "d" => struct.d,
+      "e" => struct.e,
+      "f" => struct.f,
+    }
+  end
+
+  def to_json(struct) do
+    struct
+          |> to_map()
+          |> Jason.encode!()
+  end
+end
+
+defmodule TopLevel do
+  defstruct [:first_property, :second_property]
+
+  @type t :: %__MODULE__{
+          first_property: MyObject.t() | nil,
+          second_property: [MyObjectA.t()] | MyObjectB.t() | nil
+        }
+
+  def decode_second_property(%{} = value), do: MyObjectB.from_map(value)
+  def decode_second_property(value) when is_list(value), do: value
+  def decode_second_property(value) when is_nil(value), do: value
+  def decode_second_property(_), do: {:error, "Unexpected type when decoding TopLevel.second_property"}
+
+  def encode_second_property(%MyObjectB{} = value), do: MyObjectB.to_map(value)
+  def encode_second_property(value) when is_list(value), do: value
+  def encode_second_property(value) when is_nil(value), do: value
+  def encode_second_property(_), do: {:error, "Unexpected type when encoding TopLevel.second_property"}
+
+  def from_map(m) do
+    %TopLevel{
+      first_property: m["firstProperty"] && MyObject.from_map(m["firstProperty"]),
+      second_property: decode_second_property(m["secondProperty"]),
+    }
+  end
+
+  def from_json(json) do
+    json
+          |> Jason.decode!()
+          |> from_map()
+  end
+
+  def to_map(struct) do
+    %{
+      "firstProperty" => struct.first_property && MyObject.to_map(struct.first_property),
+      "secondProperty" => encode_second_property(struct.second_property),
+    }
+  end
+
+  def to_json(struct) do
+    struct
+          |> to_map()
+          |> Jason.encode!()
+  end
+end
diff --git a/head/schema-elm/test/inputs/schema/anyof-object-union.schema/default/QuickType.elm b/head/schema-elm/test/inputs/schema/anyof-object-union.schema/default/QuickType.elm
new file mode 100644
index 0000000..42f04d3
--- /dev/null
+++ b/head/schema-elm/test/inputs/schema/anyof-object-union.schema/default/QuickType.elm
@@ -0,0 +1,146 @@
+-- To decode the JSON data, add this file to your project, run
+--
+--     elm install NoRedInk/elm-json-decode-pipeline
+--
+-- add these imports
+--
+--     import Json.Decode exposing (decodeString)
+--     import QuickType exposing (quickType)
+--
+-- and you're off to the races with
+--
+--     decodeString quickType myJsonString
+
+module QuickType exposing
+    ( QuickType
+    , quickTypeToString
+    , quickType
+    , MyObject
+    , MyObjectA
+    , MyObjectB
+    , SecondProperty(..)
+    )
+
+import Json.Decode as Jdec
+import Json.Decode.Pipeline as Jpipe
+import Json.Encode as Jenc
+import Dict exposing (Dict)
+
+type alias QuickType =
+    { firstProperty : Maybe MyObject
+    , secondProperty : Maybe SecondProperty
+    }
+
+type alias MyObject =
+    { a : Maybe String
+    , b : Maybe Float
+    , c : Maybe Bool
+    , d : Maybe String
+    , e : Maybe Float
+    , myObjectF : Maybe Bool
+    }
+
+type SecondProperty
+    = MyObjectAArrayInSecondProperty (List MyObjectA)
+    | MyObjectBInSecondProperty MyObjectB
+
+type alias MyObjectA =
+    { a : Maybe String
+    , b : Maybe Float
+    , c : Maybe Bool
+    }
+
+type alias MyObjectB =
+    { d : Maybe String
+    , e : Maybe Float
+    , myObjectBF : Maybe Bool
+    }
+
+-- decoders and encoders
+
+quickTypeToString : QuickType -> String
+quickTypeToString r = Jenc.encode 0 (encodeQuickType r)
+
+quickType : Jdec.Decoder QuickType
+quickType =
+    Jdec.succeed QuickType
+        |> Jpipe.optional "firstProperty" (Jdec.nullable myObject) Nothing
+        |> Jpipe.optional "secondProperty" (Jdec.nullable secondProperty) Nothing
+
+encodeQuickType : QuickType -> Jenc.Value
+encodeQuickType x =
+    Jenc.object
+        [ ("firstProperty", makeNullableEncoder encodeMyObject x.firstProperty)
+        , ("secondProperty", makeNullableEncoder encodeSecondProperty x.secondProperty)
+        ]
+
+myObject : Jdec.Decoder MyObject
+myObject =
+    Jdec.succeed MyObject
+        |> Jpipe.optional "a" (Jdec.nullable Jdec.string) Nothing
+        |> Jpipe.optional "b" (Jdec.nullable Jdec.float) Nothing
+        |> Jpipe.optional "c" (Jdec.nullable Jdec.bool) Nothing
+        |> Jpipe.optional "d" (Jdec.nullable Jdec.string) Nothing
+        |> Jpipe.optional "e" (Jdec.nullable Jdec.float) Nothing
+        |> Jpipe.optional "f" (Jdec.nullable Jdec.bool) Nothing
+
+encodeMyObject : MyObject -> Jenc.Value
+encodeMyObject x =
+    Jenc.object
+        [ ("a", makeNullableEncoder Jenc.string x.a)
+        , ("b", makeNullableEncoder Jenc.float x.b)
+        , ("c", makeNullableEncoder Jenc.bool x.c)
+        , ("d", makeNullableEncoder Jenc.string x.d)
+        , ("e", makeNullableEncoder Jenc.float x.e)
+        , ("f", makeNullableEncoder Jenc.bool x.myObjectF)
+        ]
+
+secondProperty : Jdec.Decoder SecondProperty
+secondProperty =
+    Jdec.oneOf
+        [ Jdec.map MyObjectAArrayInSecondProperty (Jdec.list myObjectA)
+        , Jdec.map MyObjectBInSecondProperty myObjectB
+        ]
+
+encodeSecondProperty : SecondProperty -> Jenc.Value
+encodeSecondProperty x = case x of
+    MyObjectAArrayInSecondProperty y -> Jenc.list encodeMyObjectA y
+    MyObjectBInSecondProperty y -> encodeMyObjectB y
+
+myObjectA : Jdec.Decoder MyObjectA
+myObjectA =
+    Jdec.succeed MyObjectA
+        |> Jpipe.optional "a" (Jdec.nullable Jdec.string) Nothing
+        |> Jpipe.optional "b" (Jdec.nullable Jdec.float) Nothing
+        |> Jpipe.optional "c" (Jdec.nullable Jdec.bool) Nothing
+
+encodeMyObjectA : MyObjectA -> Jenc.Value
+encodeMyObjectA x =
+    Jenc.object
+        [ ("a", makeNullableEncoder Jenc.string x.a)
+        , ("b", makeNullableEncoder Jenc.float x.b)
+        , ("c", makeNullableEncoder Jenc.bool x.c)
+        ]
+
+myObjectB : Jdec.Decoder MyObjectB
+myObjectB =
+    Jdec.succeed MyObjectB
+        |> Jpipe.optional "d" (Jdec.nullable Jdec.string) Nothing
+        |> Jpipe.optional "e" (Jdec.nullable Jdec.float) Nothing
+        |> Jpipe.optional "f" (Jdec.nullable Jdec.bool) Nothing
+
+encodeMyObjectB : MyObjectB -> Jenc.Value
+encodeMyObjectB x =
+    Jenc.object
+        [ ("d", makeNullableEncoder Jenc.string x.d)
+        , ("e", makeNullableEncoder Jenc.float x.e)
+        , ("f", makeNullableEncoder Jenc.bool x.myObjectBF)
+        ]
+
+--- encoder helpers
+
+makeNullableEncoder : (a -> Jenc.Value) -> Maybe a -> Jenc.Value
+makeNullableEncoder f m =
+    case m of
+    Just x -> f x
+    Nothing -> Jenc.null
diff --git a/head/schema-flow/test/inputs/schema/anyof-object-union.schema/default/TopLevel.js b/head/schema-flow/test/inputs/schema/anyof-object-union.schema/default/TopLevel.js
new file mode 100644
index 0000000..26082bc
--- /dev/null
+++ b/head/schema-flow/test/inputs/schema/anyof-object-union.schema/default/TopLevel.js
@@ -0,0 +1,231 @@
+// @flow
+
+// To parse this data:
+//
+//   const Convert = require("./TopLevel");
+//
+//   const topLevel = Convert.toTopLevel(json);
+//
+// These functions will throw an error if the JSON doesn't
+// match the expected interface, even if the JSON is valid.
+
+export type TopLevel = {
+    firstProperty?:  MyObject;
+    secondProperty?: SecondProperty;
+};
+
+export type MyObject = {
+    a?: string;
+    b?: number;
+    c?: boolean;
+    d?: string;
+    e?: number;
+    f?: boolean;
+};
+
+export type SecondProperty = MyObjectA[] | MyObjectB;
+
+export type MyObjectA = {
+    a?: string;
+    b?: number;
+    c?: boolean;
+};
+
+export type MyObjectB = {
+    d?: string;
+    e?: number;
+    f?: boolean;
+};
+
+// Converts JSON strings to/from your types
+// and asserts the results of JSON.parse at runtime
+function toTopLevel(json: string): TopLevel {
+    return cast(JSON.parse(json), r("TopLevel"));
+}
+
+function topLevelToJson(value: TopLevel): string {
+    return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
+}
+
+function invalidValue(typ: any, val: any, key: any, parent: any = '') {
+    const prettyTyp = prettyTypeName(typ);
+    const parentText = parent ? ` on ${parent}` : '';
+    const keyText = key ? ` for key "${key}"` : '';
+    throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
+}
+
+function prettyTypeName(typ: any): string {
+    if (Array.isArray(typ)) {
+        if (typ.length === 2 && typ[0] === undefined) {
+            return `an optional ${prettyTypeName(typ[1])}`;
+        } else {
+            return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
+        }
+    } else if (typeof typ === "object" && typ.literal !== undefined) {
+        return typ.literal;
+    } else {
+        return typeof typ;
+    }
+}
+
+function jsonToJSProps(typ: any): any {
+    if (typ.jsonToJS === undefined) {
+        const map: any = {};
+        typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
+        typ.jsonToJS = map;
+    }
+    return typ.jsonToJS;
+}
+
+function jsToJSONProps(typ: any): any {
+    if (typ.jsToJSON === undefined) {
+        const map: any = {};
+        typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
+        typ.jsToJSON = map;
+    }
+    return typ.jsToJSON;
+}
+
+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
+    function transformPrimitive(typ: string, val: any): any {
+        if (typeof typ === typeof val) return val;
+        return invalidValue(typ, val, key, parent);
+    }
+
+    function transformUnion(typs: any[], val: any): any {
+        // val must validate against one typ in typs
+        const l = typs.length;
+        for (let i = 0; i < l; i++) {
+            const typ = typs[i];
+            try {
+                return transform(val, typ, getProps);
+            } catch (_) {}
+        }
+        return invalidValue(typs, val, key, parent);
+    }
+
+    function transformEnum(cases: string[], val: any): any {
+        if (cases.indexOf(val) !== -1) return val;
+        return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
+    }
+
+    function transformArray(typ: any, val: any): any {
+        // val must be an array with no invalid elements
+        if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
+        return val.map(el => transform(el, typ, getProps));
+    }
+
+    function transformDate(val: any): any {
+        if (val === null) {
+            return null;
+        }
+        const d = new Date(val);
+        if (isNaN(d.valueOf())) {
+            return invalidValue(l("Date"), val, key, parent);
+        }
+        return d;
+    }
+
+    function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
+        if (val === null || typeof val !== "object" || Array.isArray(val)) {
+            return invalidValue(l(ref || "object"), val, key, parent);
+        }
+        const result: any = {};
+        Object.getOwnPropertyNames(props).forEach(key => {
+            const prop = props[key];
+            const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
+            result[prop.key] = transform(v, prop.typ, getProps, key, ref);
+        });
+        Object.getOwnPropertyNames(val).forEach(key => {
+            if (!Object.prototype.hasOwnProperty.call(props, key)) {
+                result[key] = transform(val[key], additional, getProps, key, ref);
+            }
+        });
+        return result;
+    }
+
+    if (typ === "any") return val;
+    if (typ === null) {
+        if (val === null) return val;
+        return invalidValue(typ, val, key, parent);
+    }
+    if (typ === false) return invalidValue(typ, val, key, parent);
+    let ref: any = undefined;
+    while (typeof typ === "object" && typ.ref !== undefined) {
+        ref = typ.ref;
+        typ = typeMap[typ.ref];
+    }
+    if (Array.isArray(typ)) return transformEnum(typ, val);
+    if (typeof typ === "object") {
+        return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
+            : typ.hasOwnProperty("arrayItems")    ? transformArray(typ.arrayItems, val)
+            : typ.hasOwnProperty("props")         ? transformObject(getProps(typ), typ.additional, val)
+            : invalidValue(typ, val, key, parent);
+    }
+    // Numbers can be parsed by Date but shouldn't be.
+    if (typ === Date && typeof val !== "number") return transformDate(val);
+    return transformPrimitive(typ, val);
+}
+
+function cast<T>(val: any, typ: any): T {
+    return transform(val, typ, jsonToJSProps);
+}
+
+function uncast<T>(val: T, typ: any): any {
+    return transform(val, typ, jsToJSONProps);
+}
+
+function l(typ: any) {
+    return { literal: typ };
+}
+
+function a(typ: any) {
+    return { arrayItems: typ };
+}
+
+function u(...typs: any[]) {
+    return { unionMembers: typs };
+}
+
+function o(props: any[], additional: any) {
+    return { props, additional };
+}
+
+function m(additional: any) {
+    const props: any[] = [];
+    return { props, additional };
+}
+
+function r(name: string) {
+    return { ref: name };
+}
+
+const typeMap: any = {
+    "TopLevel": o([
+        { json: "firstProperty", js: "firstProperty", typ: u(undefined, r("MyObject")) },
+        { json: "secondProperty", js: "secondProperty", typ: u(undefined, u(a(r("MyObjectA")), r("MyObjectB"))) },
+    ], false),
+    "MyObject": o([
+        { json: "a", js: "a", typ: u(undefined, "") },
+        { json: "b", js: "b", typ: u(undefined, 3.14) },
+        { json: "c", js: "c", typ: u(undefined, true) },
+        { json: "d", js: "d", typ: u(undefined, "") },
+        { json: "e", js: "e", typ: u(undefined, 3.14) },
+        { json: "f", js: "f", typ: u(undefined, true) },
+    ], false),
+    "MyObjectA": o([
+        { json: "a", js: "a", typ: u(undefined, "") },
+        { json: "b", js: "b", typ: u(undefined, 3.14) },
+        { json: "c", js: "c", typ: u(undefined, true) },
+    ], false),
+    "MyObjectB": o([
+        { json: "d", js: "d", typ: u(undefined, "") },
+        { json: "e", js: "e", typ: u(undefined, 3.14) },
+        { json: "f", js: "f", typ: u(undefined, true) },
+    ], false),
+};
+
+module.exports = {
+    "topLevelToJson": topLevelToJson,
+    "toTopLevel": toTopLevel,
+};
diff --git a/head/schema-golang/test/inputs/schema/anyof-object-union.schema/default/quicktype.go b/head/schema-golang/test/inputs/schema/anyof-object-union.schema/default/quicktype.go
new file mode 100644
index 0000000..dcfc20b
--- /dev/null
+++ b/head/schema-golang/test/inputs/schema/anyof-object-union.schema/default/quicktype.go
@@ -0,0 +1,184 @@
+// Code generated from JSON Schema using quicktype. DO NOT EDIT.
+// To parse and unparse this JSON data, add this code to your project and do:
+//
+//    topLevel, err := UnmarshalTopLevel(bytes)
+//    bytes, err = topLevel.Marshal()
+
+package main
+
+import "bytes"
+import "errors"
+
+import "encoding/json"
+
+func UnmarshalTopLevel(data []byte) (TopLevel, error) {
+	var r TopLevel
+	err := json.Unmarshal(data, &r)
+	return r, err
+}
+
+func (r *TopLevel) Marshal() ([]byte, error) {
+	return json.Marshal(r)
+}
+
+type TopLevel struct {
+	FirstProperty  *MyObject       `json:"firstProperty,omitempty"`
+	SecondProperty *SecondProperty `json:"secondProperty"`
+}
+
+type MyObject struct {
+	A *string  `json:"a,omitempty"`
+	B *float64 `json:"b,omitempty"`
+	C *bool    `json:"c,omitempty"`
+	D *string  `json:"d,omitempty"`
+	E *float64 `json:"e,omitempty"`
+	F *bool    `json:"f,omitempty"`
+}
+
+type MyObjectA struct {
+	A *string  `json:"a,omitempty"`
+	B *float64 `json:"b,omitempty"`
+	C *bool    `json:"c,omitempty"`
+}
+
+type MyObjectB struct {
+	D *string  `json:"d,omitempty"`
+	E *float64 `json:"e,omitempty"`
+	F *bool    `json:"f,omitempty"`
+}
+
+type SecondProperty struct {
+	MyObjectAArray []MyObjectA
+	MyObjectB      *MyObjectB
+}
+
+func (x *SecondProperty) UnmarshalJSON(data []byte) error {
+	x.MyObjectAArray = nil
+	x.MyObjectB = nil
+	var c MyObjectB
+	object, err := unmarshalUnion(data, nil, nil, nil, nil, true, &x.MyObjectAArray, true, &c, false, nil, false, nil, false)
+	if err != nil {
+		return err
+	}
+	if object {
+		x.MyObjectB = &c
+	}
+	return nil
+}
+
+func (x *SecondProperty) MarshalJSON() ([]byte, error) {
+	return marshalUnion(nil, nil, nil, nil, x.MyObjectAArray != nil, x.MyObjectAArray, x.MyObjectB != nil, x.MyObjectB, false, nil, false, nil, false)
+}
+
+func unmarshalUnion(data []byte, pi **int64, pf **float64, pb **bool, ps **string, haveArray bool, pa interface{}, haveObject bool, pc interface{}, haveMap bool, pm interface{}, haveEnum bool, pe interface{}, nullable bool) (bool, error) {
+	if pi != nil {
+			*pi = nil
+	}
+	if pf != nil {
+			*pf = nil
+	}
+	if pb != nil {
+			*pb = nil
+	}
+	if ps != nil {
+			*ps = nil
+	}
+
+	dec := json.NewDecoder(bytes.NewReader(data))
+	dec.UseNumber()
+	tok, err := dec.Token()
+	if err != nil {
+			return false, err
+	}
+
+	switch v := tok.(type) {
+	case json.Number:
+			if pi != nil {
+					i, err := v.Int64()
+					if err == nil {
+							*pi = &i
+							return false, nil
+					}
+			}
+			if pf != nil {
+					f, err := v.Float64()
+					if err == nil {
+							*pf = &f
+							return false, nil
+					}
+					return false, errors.New("Unparsable number")
+			}
+			return false, errors.New("Union does not contain number")
+	case float64:
+			return false, errors.New("Decoder should not return float64")
+	case bool:
+			if pb != nil {
+					*pb = &v
+					return false, nil
+			}
+			return false, errors.New("Union does not contain bool")
+	case string:
+			if haveEnum {
+					return false, json.Unmarshal(data, pe)
+			}
+			if ps != nil {
+					*ps = &v
+					return false, nil
+			}
+			return false, errors.New("Union does not contain string")
+	case nil:
+			if nullable {
+					return false, nil
+			}
+			return false, errors.New("Union does not contain null")
+	case json.Delim:
+			if v == '{' {
+					if haveObject {
+							return true, json.Unmarshal(data, pc)
+					}
+					if haveMap {
+							return false, json.Unmarshal(data, pm)
+					}
+					return false, errors.New("Union does not contain object")
+			}
+			if v == '[' {
+					if haveArray {
+							return false, json.Unmarshal(data, pa)
+					}
+					return false, errors.New("Union does not contain array")
+			}
+			return false, errors.New("Cannot handle delimiter")
+	}
+	return false, errors.New("Cannot unmarshal union")
+}
+
+func marshalUnion(pi *int64, pf *float64, pb *bool, ps *string, haveArray bool, pa interface{}, haveObject bool, pc interface{}, haveMap bool, pm interface{}, haveEnum bool, pe interface{}, nullable bool) ([]byte, error) {
+	if pi != nil {
+			return json.Marshal(*pi)
+	}
+	if pf != nil {
+			return json.Marshal(*pf)
+	}
+	if pb != nil {
+			return json.Marshal(*pb)
+	}
+	if ps != nil {
+			return json.Marshal(*ps)
+	}
+	if haveArray {
+			return json.Marshal(pa)
+	}
+	if haveObject {
+			return json.Marshal(pc)
+	}
+	if haveMap {
+			return json.Marshal(pm)
+	}
+	if haveEnum {
+			return json.Marshal(pe)
+	}
+	if nullable {
+			return json.Marshal(nil)
+	}
+	return nil, errors.New("Union must not be null")
+}
diff --git a/head/schema-haskell/test/inputs/schema/anyof-object-union.schema/default/QuickType.hs b/head/schema-haskell/test/inputs/schema/anyof-object-union.schema/default/QuickType.hs
new file mode 100644
index 0000000..79b917a
--- /dev/null
+++ b/head/schema-haskell/test/inputs/schema/anyof-object-union.schema/default/QuickType.hs
@@ -0,0 +1,119 @@
+{-# LANGUAGE StrictData #-}
+{-# LANGUAGE OverloadedStrings #-}
+
+module QuickType
+    ( QuickType (..)
+    , MyObject (..)
+    , MyObjectA (..)
+    , MyObjectB (..)
+    , SecondProperty (..)
+    , decodeTopLevel
+    ) where
+
+import Data.Aeson
+import Data.Aeson.Types (emptyObject)
+import Data.ByteString.Lazy (ByteString)
+import Data.HashMap.Strict (HashMap)
+import Data.Text (Text)
+
+data QuickType = QuickType
+    { firstPropertyQuickType :: Maybe MyObject
+    , secondPropertyQuickType :: Maybe SecondProperty
+    } deriving (Show)
+
+data MyObject = MyObject
+    { aMyObject :: Maybe Text
+    , bMyObject :: Maybe Float
+    , cMyObject :: Maybe Bool
+    , dMyObject :: Maybe Text
+    , eMyObject :: Maybe Float
+    , fMyObject :: Maybe Bool
+    } deriving (Show)
+
+data SecondProperty
+    = MyObjectAArrayInSecondProperty ([MyObjectA])
+    | MyObjectBInSecondProperty MyObjectB
+    deriving (Show)
+
+data MyObjectA = MyObjectA
+    { aMyObjectA :: Maybe Text
+    , bMyObjectA :: Maybe Float
+    , cMyObjectA :: Maybe Bool
+    } deriving (Show)
+
+data MyObjectB = MyObjectB
+    { dMyObjectB :: Maybe Text
+    , eMyObjectB :: Maybe Float
+    , fMyObjectB :: Maybe Bool
+    } deriving (Show)
+
+decodeTopLevel :: ByteString -> Maybe QuickType
+decodeTopLevel = decode
+
+instance ToJSON QuickType where
+    toJSON (QuickType firstPropertyQuickType secondPropertyQuickType) =
+        object
+        [ "firstProperty" .= firstPropertyQuickType
+        , "secondProperty" .= secondPropertyQuickType
+        ]
+
+instance FromJSON QuickType where
+    parseJSON (Object v) = QuickType
+        <$> v .:? "firstProperty"
+        <*> v .:? "secondProperty"
+
+instance ToJSON MyObject where
+    toJSON (MyObject aMyObject bMyObject cMyObject dMyObject eMyObject fMyObject) =
+        object
+        [ "a" .= aMyObject
+        , "b" .= bMyObject
+        , "c" .= cMyObject
+        , "d" .= dMyObject
+        , "e" .= eMyObject
+        , "f" .= fMyObject
+        ]
+
+instance FromJSON MyObject where
+    parseJSON (Object v) = MyObject
+        <$> v .:? "a"
+        <*> v .:? "b"
+        <*> v .:? "c"
+        <*> v .:? "d"
+        <*> v .:? "e"
+        <*> v .:? "f"
+
+instance ToJSON SecondProperty where
+    toJSON (MyObjectAArrayInSecondProperty x) = toJSON x
+    toJSON (MyObjectBInSecondProperty x) = toJSON x
+
+instance FromJSON SecondProperty where
+    parseJSON xs@(Array _) = (fmap MyObjectAArrayInSecondProperty . parseJSON) xs
+    parseJSON xs@(Object _) = (fmap MyObjectBInSecondProperty . parseJSON) xs
+
+instance ToJSON MyObjectA where
+    toJSON (MyObjectA aMyObjectA bMyObjectA cMyObjectA) =
+        object
+        [ "a" .= aMyObjectA
+        , "b" .= bMyObjectA
+        , "c" .= cMyObjectA
+        ]
+
+instance FromJSON MyObjectA where
+    parseJSON (Object v) = MyObjectA
+        <$> v .:? "a"
+        <*> v .:? "b"
+        <*> v .:? "c"
+
+instance ToJSON MyObjectB where
+    toJSON (MyObjectB dMyObjectB eMyObjectB fMyObjectB) =
+        object
+        [ "d" .= dMyObjectB
+        , "e" .= eMyObjectB
+        , "f" .= fMyObjectB
+        ]
+
+instance FromJSON MyObjectB where
+    parseJSON (Object v) = MyObjectB
+        <$> v .:? "d"
+        <*> v .:? "e"
+        <*> v .:? "f"
diff --git a/head/schema-java/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/Converter.java b/head/schema-java/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/Converter.java
new file mode 100644
index 0000000..a8eb236
--- /dev/null
+++ b/head/schema-java/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/Converter.java
@@ -0,0 +1,101 @@
+// To use this code, add the following Maven dependency to your project:
+//
+//
+//     com.fasterxml.jackson.core     : jackson-databind          : 2.9.0
+//     com.fasterxml.jackson.datatype : jackson-datatype-jsr310   : 2.9.0
+//
+// Import this package:
+//
+//     import io.quicktype.Converter;
+//
+// Then you can deserialize a JSON string with
+//
+//     TopLevel data = Converter.fromJsonString(jsonString);
+
+package io.quicktype;
+
+import java.io.IOException;
+import com.fasterxml.jackson.databind.*;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.*;
+import java.time.LocalDate;
+import java.time.OffsetDateTime;
+import java.time.OffsetTime;
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeFormatterBuilder;
+import java.time.temporal.ChronoField;
+
+public class Converter {
+    // Date-time helpers
+
+    private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
+            .appendOptional(DateTimeFormatter.ISO_DATE_TIME)
+            .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
+            .appendOptional(DateTimeFormatter.ISO_INSTANT)
+            .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX"))
+            .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX"))
+            .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
+            .toFormatter()
+            .withZone(ZoneOffset.UTC);
+
+    public static OffsetDateTime parseDateTimeString(String str) {
+        return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();
+    }
+
+    private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
+            .appendOptional(DateTimeFormatter.ISO_TIME)
+            .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)
+            .parseDefaulting(ChronoField.YEAR, 2020)
+            .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
+            .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
+            .toFormatter()
+            .withZone(ZoneOffset.UTC);
+
+    public static OffsetTime parseTimeString(String str) {
+        return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();
+    }
+    // Serialize/deserialize helpers
+
+    public static TopLevel fromJsonString(String json) throws IOException {
+        return getObjectReader().readValue(json);
+    }
+
+    public static String toJsonString(TopLevel obj) throws JsonProcessingException {
+        return getObjectWriter().writeValueAsString(obj);
+    }
+
+    private static ObjectReader reader;
+    private static ObjectWriter writer;
+
+    private static void instantiateMapper() {
+        ObjectMapper mapper = new ObjectMapper();
+        mapper.findAndRegisterModules();
+        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
+        SimpleModule module = new SimpleModule();
+        module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
+            @Override
+            public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
+                String value = jsonParser.getText();
+                return Converter.parseDateTimeString(value);
+            }
+        });
+        mapper.registerModule(module);
+        reader = mapper.readerFor(TopLevel.class);
+        writer = mapper.writerFor(TopLevel.class);
+    }
+
+    private static ObjectReader getObjectReader() {
+        if (reader == null) instantiateMapper();
+        return reader;
+    }
+
+    private static ObjectWriter getObjectWriter() {
+        if (writer == null) instantiateMapper();
+        return writer;
+    }
+}
diff --git a/head/schema-java/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObject.java b/head/schema-java/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObject.java
new file mode 100644
index 0000000..4a829b5
--- /dev/null
+++ b/head/schema-java/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObject.java
@@ -0,0 +1,42 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+
+public class MyObject {
+    private String a;
+    private Double b;
+    private Boolean c;
+    private String d;
+    private Double e;
+    private Boolean f;
+
+    @JsonProperty("a")
+    public String getA() { return a; }
+    @JsonProperty("a")
+    public void setA(String value) { this.a = value; }
+
+    @JsonProperty("b")
+    public Double getB() { return b; }
+    @JsonProperty("b")
+    public void setB(Double value) { this.b = value; }
+
+    @JsonProperty("c")
+    public Boolean getC() { return c; }
+    @JsonProperty("c")
+    public void setC(Boolean value) { this.c = value; }
+
+    @JsonProperty("d")
+    public String getD() { return d; }
+    @JsonProperty("d")
+    public void setD(String value) { this.d = value; }
+
+    @JsonProperty("e")
+    public Double getE() { return e; }
+    @JsonProperty("e")
+    public void setE(Double value) { this.e = value; }
+
+    @JsonProperty("f")
+    public Boolean getF() { return f; }
+    @JsonProperty("f")
+    public void setF(Boolean value) { this.f = value; }
+}
diff --git a/head/schema-java/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObjectA.java b/head/schema-java/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObjectA.java
new file mode 100644
index 0000000..073dd3b
--- /dev/null
+++ b/head/schema-java/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObjectA.java
@@ -0,0 +1,24 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+
+public class MyObjectA {
+    private String a;
+    private Double b;
+    private Boolean c;
+
+    @JsonProperty("a")
+    public String getA() { return a; }
+    @JsonProperty("a")
+    public void setA(String value) { this.a = value; }
+
+    @JsonProperty("b")
+    public Double getB() { return b; }
+    @JsonProperty("b")
+    public void setB(Double value) { this.b = value; }
+
+    @JsonProperty("c")
+    public Boolean getC() { return c; }
+    @JsonProperty("c")
+    public void setC(Boolean value) { this.c = value; }
+}
diff --git a/head/schema-java/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObjectB.java b/head/schema-java/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObjectB.java
new file mode 100644
index 0000000..f971bad
--- /dev/null
+++ b/head/schema-java/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObjectB.java
@@ -0,0 +1,24 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+
+public class MyObjectB {
+    private String d;
+    private Double e;
+    private Boolean f;
+
+    @JsonProperty("d")
+    public String getD() { return d; }
+    @JsonProperty("d")
+    public void setD(String value) { this.d = value; }
+
+    @JsonProperty("e")
+    public Double getE() { return e; }
+    @JsonProperty("e")
+    public void setE(Double value) { this.e = value; }
+
+    @JsonProperty("f")
+    public Boolean getF() { return f; }
+    @JsonProperty("f")
+    public void setF(Boolean value) { this.f = value; }
+}
diff --git a/head/schema-java/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/SecondProperty.java b/head/schema-java/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/SecondProperty.java
new file mode 100644
index 0000000..d743baa
--- /dev/null
+++ b/head/schema-java/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/SecondProperty.java
@@ -0,0 +1,50 @@
+package io.quicktype;
+
+import java.io.IOException;
+import java.io.IOException;
+import com.fasterxml.jackson.core.*;
+import com.fasterxml.jackson.databind.*;
+import com.fasterxml.jackson.databind.annotation.*;
+import com.fasterxml.jackson.core.type.*;
+import java.util.List;
+
+@JsonDeserialize(using = SecondProperty.Deserializer.class)
+@JsonSerialize(using = SecondProperty.Serializer.class)
+public class SecondProperty {
+    public List<MyObjectA> myObjectAArrayValue;
+    public MyObjectB myObjectBValue;
+
+    static class Deserializer extends JsonDeserializer<SecondProperty> {
+        @Override
+        public SecondProperty deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
+            SecondProperty value = new SecondProperty();
+            switch (jsonParser.currentToken()) {
+                case VALUE_NULL:
+                    break;
+                case START_ARRAY:
+                    value.myObjectAArrayValue = jsonParser.readValueAs(new TypeReference<List<MyObjectA>>() {});
+                    break;
+                case START_OBJECT:
+                    value.myObjectBValue = jsonParser.readValueAs(MyObjectB.class);
+                    break;
+                default: throw new IOException("Cannot deserialize SecondProperty");
+            }
+            return value;
+        }
+    }
+
+    static class Serializer extends JsonSerializer<SecondProperty> {
+        @Override
+        public void serialize(SecondProperty obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
+            if (obj.myObjectAArrayValue != null) {
+                jsonGenerator.writeObject(obj.myObjectAArrayValue);
+                return;
+            }
+            if (obj.myObjectBValue != null) {
+                jsonGenerator.writeObject(obj.myObjectBValue);
+                return;
+            }
+            jsonGenerator.writeNull();
+        }
+    }
+}
diff --git a/head/schema-java/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/TopLevel.java b/head/schema-java/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/TopLevel.java
new file mode 100644
index 0000000..867df0e
--- /dev/null
+++ b/head/schema-java/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/TopLevel.java
@@ -0,0 +1,19 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+import java.util.List;
+
+public class TopLevel {
+    private MyObject firstProperty;
+    private SecondProperty secondProperty;
+
+    @JsonProperty("firstProperty")
+    public MyObject getFirstProperty() { return firstProperty; }
+    @JsonProperty("firstProperty")
+    public void setFirstProperty(MyObject value) { this.firstProperty = value; }
+
+    @JsonProperty("secondProperty")
+    public SecondProperty getSecondProperty() { return secondProperty; }
+    @JsonProperty("secondProperty")
+    public void setSecondProperty(SecondProperty value) { this.secondProperty = value; }
+}
diff --git a/head/schema-java-datetime-legacy/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/Converter.java b/head/schema-java-datetime-legacy/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/Converter.java
new file mode 100644
index 0000000..7d4811b
--- /dev/null
+++ b/head/schema-java-datetime-legacy/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/Converter.java
@@ -0,0 +1,121 @@
+// To use this code, add the following Maven dependency to your project:
+//
+//
+//     com.fasterxml.jackson.core     : jackson-databind          : 2.9.0
+//
+//
+// Import this package:
+//
+//     import io.quicktype.Converter;
+//
+// Then you can deserialize a JSON string with
+//
+//     TopLevel data = Converter.fromJsonString(jsonString);
+
+package io.quicktype;
+
+import java.io.IOException;
+import com.fasterxml.jackson.databind.*;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.*;
+import java.util.Date;
+import java.text.SimpleDateFormat;
+
+public class Converter {
+    // Date-time helpers
+
+    private static final String[] DATE_TIME_FORMATS = {
+            "yyyy-MM-dd'T'HH:mm:ss.SX",
+            "yyyy-MM-dd'T'HH:mm:ss.S",
+            "yyyy-MM-dd'T'HH:mm:ssX",
+            "yyyy-MM-dd'T'HH:mm:ss",
+            "yyyy-MM-dd HH:mm:ss.SX",
+            "yyyy-MM-dd HH:mm:ss.S",
+            "yyyy-MM-dd HH:mm:ssX",
+            "yyyy-MM-dd HH:mm:ss",
+            "HH:mm:ss.SZ",
+            "HH:mm:ss.S",
+            "HH:mm:ssZ",
+            "HH:mm:ss",
+            "yyyy-MM-dd",
+    };
+
+    public static Date parseAllDateTimeString(String str) {
+        for (String format : DATE_TIME_FORMATS) {
+            try {
+                return new SimpleDateFormat(format).parse(str);
+            } catch (Exception ex) {
+                // Ignored
+            }
+        }
+        return null;
+    }
+
+    public static String serializeDateTime(Date datetime) {
+        return new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ").format(datetime);
+    }
+
+    public static String serializeDate(Date datetime) {
+        return new SimpleDateFormat("yyyy-MM-dd").format(datetime);
+    }
+
+    public static String serializeTime(Date datetime) {
+        return new SimpleDateFormat("hh:mm:ssZ").format(datetime);
+    }
+    // Serialize/deserialize helpers
+
+    public static TopLevel fromJsonString(String json) throws IOException {
+        return getObjectReader().readValue(json);
+    }
+
+    public static String toJsonString(TopLevel obj) throws JsonProcessingException {
+        return getObjectWriter().writeValueAsString(obj);
+    }
+
+    private static ObjectReader reader;
+    private static ObjectWriter writer;
+
+    private static void instantiateMapper() {
+        ObjectMapper mapper = new ObjectMapper();
+        mapper.findAndRegisterModules();
+        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
+        SimpleModule module = new SimpleModule();
+        module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
+            @Override
+            public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
+                String value = jsonParser.getText();
+                return Converter.parseAllDateTimeString(value);
+            }
+        });
+        module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
+            @Override
+            public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
+                String value = jsonParser.getText();
+                return Converter.parseAllDateTimeString(value);
+            }
+        });
+        module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
+            @Override
+            public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
+                String value = jsonParser.getText();
+                return Converter.parseAllDateTimeString(value);
+            }
+        });
+        mapper.registerModule(module);
+        reader = mapper.readerFor(TopLevel.class);
+        writer = mapper.writerFor(TopLevel.class);
+    }
+
+    private static ObjectReader getObjectReader() {
+        if (reader == null) instantiateMapper();
+        return reader;
+    }
+
+    private static ObjectWriter getObjectWriter() {
+        if (writer == null) instantiateMapper();
+        return writer;
+    }
+}
diff --git a/head/schema-java-datetime-legacy/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObject.java b/head/schema-java-datetime-legacy/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObject.java
new file mode 100644
index 0000000..4a829b5
--- /dev/null
+++ b/head/schema-java-datetime-legacy/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObject.java
@@ -0,0 +1,42 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+
+public class MyObject {
+    private String a;
+    private Double b;
+    private Boolean c;
+    private String d;
+    private Double e;
+    private Boolean f;
+
+    @JsonProperty("a")
+    public String getA() { return a; }
+    @JsonProperty("a")
+    public void setA(String value) { this.a = value; }
+
+    @JsonProperty("b")
+    public Double getB() { return b; }
+    @JsonProperty("b")
+    public void setB(Double value) { this.b = value; }
+
+    @JsonProperty("c")
+    public Boolean getC() { return c; }
+    @JsonProperty("c")
+    public void setC(Boolean value) { this.c = value; }
+
+    @JsonProperty("d")
+    public String getD() { return d; }
+    @JsonProperty("d")
+    public void setD(String value) { this.d = value; }
+
+    @JsonProperty("e")
+    public Double getE() { return e; }
+    @JsonProperty("e")
+    public void setE(Double value) { this.e = value; }
+
+    @JsonProperty("f")
+    public Boolean getF() { return f; }
+    @JsonProperty("f")
+    public void setF(Boolean value) { this.f = value; }
+}
diff --git a/head/schema-java-datetime-legacy/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObjectA.java b/head/schema-java-datetime-legacy/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObjectA.java
new file mode 100644
index 0000000..073dd3b
--- /dev/null
+++ b/head/schema-java-datetime-legacy/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObjectA.java
@@ -0,0 +1,24 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+
+public class MyObjectA {
+    private String a;
+    private Double b;
+    private Boolean c;
+
+    @JsonProperty("a")
+    public String getA() { return a; }
+    @JsonProperty("a")
+    public void setA(String value) { this.a = value; }
+
+    @JsonProperty("b")
+    public Double getB() { return b; }
+    @JsonProperty("b")
+    public void setB(Double value) { this.b = value; }
+
+    @JsonProperty("c")
+    public Boolean getC() { return c; }
+    @JsonProperty("c")
+    public void setC(Boolean value) { this.c = value; }
+}
diff --git a/head/schema-java-datetime-legacy/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObjectB.java b/head/schema-java-datetime-legacy/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObjectB.java
new file mode 100644
index 0000000..f971bad
--- /dev/null
+++ b/head/schema-java-datetime-legacy/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObjectB.java
@@ -0,0 +1,24 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+
+public class MyObjectB {
+    private String d;
+    private Double e;
+    private Boolean f;
+
+    @JsonProperty("d")
+    public String getD() { return d; }
+    @JsonProperty("d")
+    public void setD(String value) { this.d = value; }
+
+    @JsonProperty("e")
+    public Double getE() { return e; }
+    @JsonProperty("e")
+    public void setE(Double value) { this.e = value; }
+
+    @JsonProperty("f")
+    public Boolean getF() { return f; }
+    @JsonProperty("f")
+    public void setF(Boolean value) { this.f = value; }
+}
diff --git a/head/schema-java-datetime-legacy/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/SecondProperty.java b/head/schema-java-datetime-legacy/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/SecondProperty.java
new file mode 100644
index 0000000..d743baa
--- /dev/null
+++ b/head/schema-java-datetime-legacy/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/SecondProperty.java
@@ -0,0 +1,50 @@
+package io.quicktype;
+
+import java.io.IOException;
+import java.io.IOException;
+import com.fasterxml.jackson.core.*;
+import com.fasterxml.jackson.databind.*;
+import com.fasterxml.jackson.databind.annotation.*;
+import com.fasterxml.jackson.core.type.*;
+import java.util.List;
+
+@JsonDeserialize(using = SecondProperty.Deserializer.class)
+@JsonSerialize(using = SecondProperty.Serializer.class)
+public class SecondProperty {
+    public List<MyObjectA> myObjectAArrayValue;
+    public MyObjectB myObjectBValue;
+
+    static class Deserializer extends JsonDeserializer<SecondProperty> {
+        @Override
+        public SecondProperty deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
+            SecondProperty value = new SecondProperty();
+            switch (jsonParser.currentToken()) {
+                case VALUE_NULL:
+                    break;
+                case START_ARRAY:
+                    value.myObjectAArrayValue = jsonParser.readValueAs(new TypeReference<List<MyObjectA>>() {});
+                    break;
+                case START_OBJECT:
+                    value.myObjectBValue = jsonParser.readValueAs(MyObjectB.class);
+                    break;
+                default: throw new IOException("Cannot deserialize SecondProperty");
+            }
+            return value;
+        }
+    }
+
+    static class Serializer extends JsonSerializer<SecondProperty> {
+        @Override
+        public void serialize(SecondProperty obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
+            if (obj.myObjectAArrayValue != null) {
+                jsonGenerator.writeObject(obj.myObjectAArrayValue);
+                return;
+            }
+            if (obj.myObjectBValue != null) {
+                jsonGenerator.writeObject(obj.myObjectBValue);
+                return;
+            }
+            jsonGenerator.writeNull();
+        }
+    }
+}
diff --git a/head/schema-java-datetime-legacy/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/TopLevel.java b/head/schema-java-datetime-legacy/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/TopLevel.java
new file mode 100644
index 0000000..867df0e
--- /dev/null
+++ b/head/schema-java-datetime-legacy/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/TopLevel.java
@@ -0,0 +1,19 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+import java.util.List;
+
+public class TopLevel {
+    private MyObject firstProperty;
+    private SecondProperty secondProperty;
+
+    @JsonProperty("firstProperty")
+    public MyObject getFirstProperty() { return firstProperty; }
+    @JsonProperty("firstProperty")
+    public void setFirstProperty(MyObject value) { this.firstProperty = value; }
+
+    @JsonProperty("secondProperty")
+    public SecondProperty getSecondProperty() { return secondProperty; }
+    @JsonProperty("secondProperty")
+    public void setSecondProperty(SecondProperty value) { this.secondProperty = value; }
+}
diff --git a/head/schema-java-lombok/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/Converter.java b/head/schema-java-lombok/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/Converter.java
new file mode 100644
index 0000000..a8eb236
--- /dev/null
+++ b/head/schema-java-lombok/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/Converter.java
@@ -0,0 +1,101 @@
+// To use this code, add the following Maven dependency to your project:
+//
+//
+//     com.fasterxml.jackson.core     : jackson-databind          : 2.9.0
+//     com.fasterxml.jackson.datatype : jackson-datatype-jsr310   : 2.9.0
+//
+// Import this package:
+//
+//     import io.quicktype.Converter;
+//
+// Then you can deserialize a JSON string with
+//
+//     TopLevel data = Converter.fromJsonString(jsonString);
+
+package io.quicktype;
+
+import java.io.IOException;
+import com.fasterxml.jackson.databind.*;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.*;
+import java.time.LocalDate;
+import java.time.OffsetDateTime;
+import java.time.OffsetTime;
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeFormatterBuilder;
+import java.time.temporal.ChronoField;
+
+public class Converter {
+    // Date-time helpers
+
+    private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
+            .appendOptional(DateTimeFormatter.ISO_DATE_TIME)
+            .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
+            .appendOptional(DateTimeFormatter.ISO_INSTANT)
+            .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX"))
+            .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX"))
+            .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
+            .toFormatter()
+            .withZone(ZoneOffset.UTC);
+
+    public static OffsetDateTime parseDateTimeString(String str) {
+        return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();
+    }
+
+    private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
+            .appendOptional(DateTimeFormatter.ISO_TIME)
+            .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)
+            .parseDefaulting(ChronoField.YEAR, 2020)
+            .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
+            .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
+            .toFormatter()
+            .withZone(ZoneOffset.UTC);
+
+    public static OffsetTime parseTimeString(String str) {
+        return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();
+    }
+    // Serialize/deserialize helpers
+
+    public static TopLevel fromJsonString(String json) throws IOException {
+        return getObjectReader().readValue(json);
+    }
+
+    public static String toJsonString(TopLevel obj) throws JsonProcessingException {
+        return getObjectWriter().writeValueAsString(obj);
+    }
+
+    private static ObjectReader reader;
+    private static ObjectWriter writer;
+
+    private static void instantiateMapper() {
+        ObjectMapper mapper = new ObjectMapper();
+        mapper.findAndRegisterModules();
+        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
+        SimpleModule module = new SimpleModule();
+        module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
+            @Override
+            public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
+                String value = jsonParser.getText();
+                return Converter.parseDateTimeString(value);
+            }
+        });
+        mapper.registerModule(module);
+        reader = mapper.readerFor(TopLevel.class);
+        writer = mapper.writerFor(TopLevel.class);
+    }
+
+    private static ObjectReader getObjectReader() {
+        if (reader == null) instantiateMapper();
+        return reader;
+    }
+
+    private static ObjectWriter getObjectWriter() {
+        if (writer == null) instantiateMapper();
+        return writer;
+    }
+}
diff --git a/head/schema-java-lombok/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObject.java b/head/schema-java-lombok/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObject.java
new file mode 100644
index 0000000..4a829b5
--- /dev/null
+++ b/head/schema-java-lombok/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObject.java
@@ -0,0 +1,42 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+
+public class MyObject {
+    private String a;
+    private Double b;
+    private Boolean c;
+    private String d;
+    private Double e;
+    private Boolean f;
+
+    @JsonProperty("a")
+    public String getA() { return a; }
+    @JsonProperty("a")
+    public void setA(String value) { this.a = value; }
+
+    @JsonProperty("b")
+    public Double getB() { return b; }
+    @JsonProperty("b")
+    public void setB(Double value) { this.b = value; }
+
+    @JsonProperty("c")
+    public Boolean getC() { return c; }
+    @JsonProperty("c")
+    public void setC(Boolean value) { this.c = value; }
+
+    @JsonProperty("d")
+    public String getD() { return d; }
+    @JsonProperty("d")
+    public void setD(String value) { this.d = value; }
+
+    @JsonProperty("e")
+    public Double getE() { return e; }
+    @JsonProperty("e")
+    public void setE(Double value) { this.e = value; }
+
+    @JsonProperty("f")
+    public Boolean getF() { return f; }
+    @JsonProperty("f")
+    public void setF(Boolean value) { this.f = value; }
+}
diff --git a/head/schema-java-lombok/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObjectA.java b/head/schema-java-lombok/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObjectA.java
new file mode 100644
index 0000000..073dd3b
--- /dev/null
+++ b/head/schema-java-lombok/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObjectA.java
@@ -0,0 +1,24 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+
+public class MyObjectA {
+    private String a;
+    private Double b;
+    private Boolean c;
+
+    @JsonProperty("a")
+    public String getA() { return a; }
+    @JsonProperty("a")
+    public void setA(String value) { this.a = value; }
+
+    @JsonProperty("b")
+    public Double getB() { return b; }
+    @JsonProperty("b")
+    public void setB(Double value) { this.b = value; }
+
+    @JsonProperty("c")
+    public Boolean getC() { return c; }
+    @JsonProperty("c")
+    public void setC(Boolean value) { this.c = value; }
+}
diff --git a/head/schema-java-lombok/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObjectB.java b/head/schema-java-lombok/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObjectB.java
new file mode 100644
index 0000000..f971bad
--- /dev/null
+++ b/head/schema-java-lombok/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/MyObjectB.java
@@ -0,0 +1,24 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+
+public class MyObjectB {
+    private String d;
+    private Double e;
+    private Boolean f;
+
+    @JsonProperty("d")
+    public String getD() { return d; }
+    @JsonProperty("d")
+    public void setD(String value) { this.d = value; }
+
+    @JsonProperty("e")
+    public Double getE() { return e; }
+    @JsonProperty("e")
+    public void setE(Double value) { this.e = value; }
+
+    @JsonProperty("f")
+    public Boolean getF() { return f; }
+    @JsonProperty("f")
+    public void setF(Boolean value) { this.f = value; }
+}
diff --git a/head/schema-java-lombok/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/SecondProperty.java b/head/schema-java-lombok/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/SecondProperty.java
new file mode 100644
index 0000000..d743baa
--- /dev/null
+++ b/head/schema-java-lombok/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/SecondProperty.java
@@ -0,0 +1,50 @@
+package io.quicktype;
+
+import java.io.IOException;
+import java.io.IOException;
+import com.fasterxml.jackson.core.*;
+import com.fasterxml.jackson.databind.*;
+import com.fasterxml.jackson.databind.annotation.*;
+import com.fasterxml.jackson.core.type.*;
+import java.util.List;
+
+@JsonDeserialize(using = SecondProperty.Deserializer.class)
+@JsonSerialize(using = SecondProperty.Serializer.class)
+public class SecondProperty {
+    public List<MyObjectA> myObjectAArrayValue;
+    public MyObjectB myObjectBValue;
+
+    static class Deserializer extends JsonDeserializer<SecondProperty> {
+        @Override
+        public SecondProperty deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
+            SecondProperty value = new SecondProperty();
+            switch (jsonParser.currentToken()) {
+                case VALUE_NULL:
+                    break;
+                case START_ARRAY:
+                    value.myObjectAArrayValue = jsonParser.readValueAs(new TypeReference<List<MyObjectA>>() {});
+                    break;
+                case START_OBJECT:
+                    value.myObjectBValue = jsonParser.readValueAs(MyObjectB.class);
+                    break;
+                default: throw new IOException("Cannot deserialize SecondProperty");
+            }
+            return value;
+        }
+    }
+
+    static class Serializer extends JsonSerializer<SecondProperty> {
+        @Override
+        public void serialize(SecondProperty obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
+            if (obj.myObjectAArrayValue != null) {
+                jsonGenerator.writeObject(obj.myObjectAArrayValue);
+                return;
+            }
+            if (obj.myObjectBValue != null) {
+                jsonGenerator.writeObject(obj.myObjectBValue);
+                return;
+            }
+            jsonGenerator.writeNull();
+        }
+    }
+}
diff --git a/head/schema-java-lombok/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/TopLevel.java b/head/schema-java-lombok/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/TopLevel.java
new file mode 100644
index 0000000..867df0e
--- /dev/null
+++ b/head/schema-java-lombok/test/inputs/schema/anyof-object-union.schema/default/src/main/java/io/quicktype/TopLevel.java
@@ -0,0 +1,19 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+import java.util.List;
+
+public class TopLevel {
+    private MyObject firstProperty;
+    private SecondProperty secondProperty;
+
+    @JsonProperty("firstProperty")
+    public MyObject getFirstProperty() { return firstProperty; }
+    @JsonProperty("firstProperty")
+    public void setFirstProperty(MyObject value) { this.firstProperty = value; }
+
+    @JsonProperty("secondProperty")
+    public SecondProperty getSecondProperty() { return secondProperty; }
+    @JsonProperty("secondProperty")
+    public void setSecondProperty(SecondProperty value) { this.secondProperty = value; }
+}
diff --git a/head/schema-javascript/test/inputs/schema/anyof-object-union.schema/default/TopLevel.js b/head/schema-javascript/test/inputs/schema/anyof-object-union.schema/default/TopLevel.js
new file mode 100644
index 0000000..f67e3f4
--- /dev/null
+++ b/head/schema-javascript/test/inputs/schema/anyof-object-union.schema/default/TopLevel.js
@@ -0,0 +1,201 @@
+// To parse this data:
+//
+//   const Convert = require("./TopLevel");
+//
+//   const topLevel = Convert.toTopLevel(json);
+//
+// These functions will throw an error if the JSON doesn't
+// match the expected interface, even if the JSON is valid.
+
+// Converts JSON strings to/from your types
+// and asserts the results of JSON.parse at runtime
+function toTopLevel(json) {
+    return cast(JSON.parse(json), r("TopLevel"));
+}
+
+function topLevelToJson(value) {
+    return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
+}
+
+function invalidValue(typ, val, key, parent = '') {
+    const prettyTyp = prettyTypeName(typ);
+    const parentText = parent ? ` on ${parent}` : '';
+    const keyText = key ? ` for key "${key}"` : '';
+    throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
+}
+
+function prettyTypeName(typ) {
+    if (Array.isArray(typ)) {
+        if (typ.length === 2 && typ[0] === undefined) {
+            return `an optional ${prettyTypeName(typ[1])}`;
+        } else {
+            return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
+        }
+    } else if (typeof typ === "object" && typ.literal !== undefined) {
+        return typ.literal;
+    } else {
+        return typeof typ;
+    }
+}
+
+function jsonToJSProps(typ) {
+    if (typ.jsonToJS === undefined) {
+        const map = {};
+        typ.props.forEach((p) => map[p.json] = { key: p.js, typ: p.typ });
+        typ.jsonToJS = map;
+    }
+    return typ.jsonToJS;
+}
+
+function jsToJSONProps(typ) {
+    if (typ.jsToJSON === undefined) {
+        const map = {};
+        typ.props.forEach((p) => map[p.js] = { key: p.json, typ: p.typ });
+        typ.jsToJSON = map;
+    }
+    return typ.jsToJSON;
+}
+
+function transform(val, typ, getProps, key = '', parent = '') {
+    function transformPrimitive(typ, val) {
+        if (typeof typ === typeof val) return val;
+        return invalidValue(typ, val, key, parent);
+    }
+
+    function transformUnion(typs, val) {
+        // val must validate against one typ in typs
+        const l = typs.length;
+        for (let i = 0; i < l; i++) {
+            const typ = typs[i];
+            try {
+                return transform(val, typ, getProps);
+            } catch (_) {}
+        }
+        return invalidValue(typs, val, key, parent);
+    }
+
+    function transformEnum(cases, val) {
+        if (cases.indexOf(val) !== -1) return val;
+        return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
+    }
+
+    function transformArray(typ, val) {
+        // val must be an array with no invalid elements
+        if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
+        return val.map(el => transform(el, typ, getProps));
+    }
+
+    function transformDate(val) {
+        if (val === null) {
+            return null;
+        }
+        const d = new Date(val);
+        if (isNaN(d.valueOf())) {
+            return invalidValue(l("Date"), val, key, parent);
+        }
+        return d;
+    }
+
+    function transformObject(props, additional, val) {
+        if (val === null || typeof val !== "object" || Array.isArray(val)) {
+            return invalidValue(l(ref || "object"), val, key, parent);
+        }
+        const result = {};
+        Object.getOwnPropertyNames(props).forEach(key => {
+            const prop = props[key];
+            const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
+            result[prop.key] = transform(v, prop.typ, getProps, key, ref);
+        });
+        Object.getOwnPropertyNames(val).forEach(key => {
+            if (!Object.prototype.hasOwnProperty.call(props, key)) {
+                result[key] = transform(val[key], additional, getProps, key, ref);
+            }
+        });
+        return result;
+    }
+
+    if (typ === "any") return val;
+    if (typ === null) {
+        if (val === null) return val;
+        return invalidValue(typ, val, key, parent);
+    }
+    if (typ === false) return invalidValue(typ, val, key, parent);
+    let ref = undefined;
+    while (typeof typ === "object" && typ.ref !== undefined) {
+        ref = typ.ref;
+        typ = typeMap[typ.ref];
+    }
+    if (Array.isArray(typ)) return transformEnum(typ, val);
+    if (typeof typ === "object") {
+        return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
+            : typ.hasOwnProperty("arrayItems")    ? transformArray(typ.arrayItems, val)
+            : typ.hasOwnProperty("props")         ? transformObject(getProps(typ), typ.additional, val)
+            : invalidValue(typ, val, key, parent);
+    }
+    // Numbers can be parsed by Date but shouldn't be.
+    if (typ === Date && typeof val !== "number") return transformDate(val);
+    return transformPrimitive(typ, val);
+}
+
+function cast(val, typ) {
+    return transform(val, typ, jsonToJSProps);
+}
+
+function uncast(val, typ) {
+    return transform(val, typ, jsToJSONProps);
+}
+
+function l(typ) {
+    return { literal: typ };
+}
+
+function a(typ) {
+    return { arrayItems: typ };
+}
+
+function u(...typs) {
+    return { unionMembers: typs };
+}
+
+function o(props, additional) {
+    return { props, additional };
+}
+
+function m(additional) {
+    const props = [];
+    return { props, additional };
+}
+
+function r(name) {
+    return { ref: name };
+}
+
+const typeMap = {
+    "TopLevel": o([
+        { json: "firstProperty", js: "firstProperty", typ: u(undefined, r("MyObject")) },
+        { json: "secondProperty", js: "secondProperty", typ: u(undefined, u(a(r("MyObjectA")), r("MyObjectB"))) },
+    ], false),
+    "MyObject": o([
+        { json: "a", js: "a", typ: u(undefined, "") },
+        { json: "b", js: "b", typ: u(undefined, 3.14) },
+        { json: "c", js: "c", typ: u(undefined, true) },
+        { json: "d", js: "d", typ: u(undefined, "") },
+        { json: "e", js: "e", typ: u(undefined, 3.14) },
+        { json: "f", js: "f", typ: u(undefined, true) },
+    ], false),
+    "MyObjectA": o([
+        { json: "a", js: "a", typ: u(undefined, "") },
+        { json: "b", js: "b", typ: u(undefined, 3.14) },
+        { json: "c", js: "c", typ: u(undefined, true) },
+    ], false),
+    "MyObjectB": o([
+        { json: "d", js: "d", typ: u(undefined, "") },
+        { json: "e", js: "e", typ: u(undefined, 3.14) },
+        { json: "f", js: "f", typ: u(undefined, true) },
+    ], false),
+};
+
+module.exports = {
+    "topLevelToJson": topLevelToJson,
+    "toTopLevel": toTopLevel,
+};
diff --git a/head/schema-kotlin-jackson/test/inputs/schema/anyof-object-union.schema/default/TopLevel.kt b/head/schema-kotlin-jackson/test/inputs/schema/anyof-object-union.schema/default/TopLevel.kt
new file mode 100644
index 0000000..3d6c61b
--- /dev/null
+++ b/head/schema-kotlin-jackson/test/inputs/schema/anyof-object-union.schema/default/TopLevel.kt
@@ -0,0 +1,81 @@
+// To parse the JSON, install jackson-module-kotlin and do:
+//
+//   val topLevel = TopLevel.fromJson(jsonString)
+
+package quicktype
+
+import com.fasterxml.jackson.annotation.*
+import com.fasterxml.jackson.core.*
+import com.fasterxml.jackson.databind.*
+import com.fasterxml.jackson.databind.deser.std.StdDeserializer
+import com.fasterxml.jackson.databind.module.SimpleModule
+import com.fasterxml.jackson.databind.node.*
+import com.fasterxml.jackson.databind.ser.std.StdSerializer
+import com.fasterxml.jackson.module.kotlin.*
+
+
+@Suppress("UNCHECKED_CAST")
+private fun <T> ObjectMapper.convert(k: kotlin.reflect.KClass<*>, fromJson: (JsonNode) -> T, toJson: (T) -> String, isUnion: Boolean = false) = registerModule(SimpleModule().apply {
+    addSerializer(k.java as Class<T>, object : StdSerializer<T>(k.java as Class<T>) {
+            override fun serialize(value: T, gen: JsonGenerator, provider: SerializerProvider) = gen.writeRawValue(toJson(value))
+    })
+    addDeserializer(k.java as Class<T>, object : StdDeserializer<T>(k.java as Class<T>) {
+            override fun deserialize(p: JsonParser, ctxt: DeserializationContext) = fromJson(p.readValueAsTree())
+    })
+})
+
+val mapper = jacksonObjectMapper().apply {
+    propertyNamingStrategy = PropertyNamingStrategy.LOWER_CAMEL_CASE
+    setSerializationInclusion(JsonInclude.Include.NON_NULL)
+    convert(SecondProperty::class, { SecondProperty.fromJson(it) }, { it.toJson() }, true)
+}
+
+data class TopLevel (
+    val firstProperty: MyObject? = null,
+    val secondProperty: SecondProperty? = null
+) {
+    fun toJson() = mapper.writeValueAsString(this)
+
+    companion object {
+        fun fromJson(json: String) = mapper.readValue<TopLevel>(json)
+    }
+}
+
+data class MyObject (
+    val a: String? = null,
+    val b: Double? = null,
+    val c: Boolean? = null,
+    val d: String? = null,
+    val e: Double? = null,
+    val f: Boolean? = null
+)
+
+sealed class SecondProperty {
+    class MyObjectAArrayValue(val value: List<MyObjectA>) : SecondProperty()
+    class MyObjectBValue(val value: MyObjectB)            : SecondProperty()
+
+    fun toJson(): String = mapper.writeValueAsString(when (this) {
+        is MyObjectAArrayValue -> this.value
+        is MyObjectBValue      -> this.value
+    })
+
+    companion object {
+        fun fromJson(jn: JsonNode): SecondProperty = when (jn) {
+            is ArrayNode  -> MyObjectAArrayValue(mapper.treeToValue(jn))
+            is ObjectNode -> MyObjectBValue(mapper.treeToValue(jn))
+            else          -> throw IllegalArgumentException()
+        }
+    }
+}
+
+data class MyObjectA (
+    val a: String? = null,
+    val b: Double? = null,
+    val c: Boolean? = null
+)
+
+data class MyObjectB (
+    val d: String? = null,
+    val e: Double? = null,
+    val f: Boolean? = null
+)
diff --git a/head/schema-php/test/inputs/schema/anyof-object-union.schema/default/TopLevel.php b/head/schema-php/test/inputs/schema/anyof-object-union.schema/default/TopLevel.php
new file mode 100644
index 0000000..82570ba
--- /dev/null
+++ b/head/schema-php/test/inputs/schema/anyof-object-union.schema/default/TopLevel.php
@@ -0,0 +1,1101 @@
+<?php
+declare(strict_types=1);
+
+// This is an autogenerated file:TopLevel
+
+class TopLevel {
+    private ?MyObject $firstProperty; // json:firstProperty Optional
+    private MyObjectB|array|null $secondProperty; // json:secondProperty Optional
+
+    /**
+     * @param MyObject|null $firstProperty
+     * @param MyObjectB|array|null $secondProperty
+     */
+    public function __construct(?MyObject $firstProperty, MyObjectB|array|null $secondProperty) {
+        $this->firstProperty = $firstProperty;
+        $this->secondProperty = $secondProperty;
+    }
+
+    /**
+     * @param ?stdClass $value
+     * @throws Exception
+     * @return ?MyObject
+     */
+    public static function fromFirstProperty(?stdClass $value): ?MyObject {
+        if (!is_null($value)) {
+            return MyObject::from($value); /*class*/
+        } else {
+            return  null;
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return ?stdClass
+     */
+    public function toFirstProperty(): ?stdClass {
+        if (TopLevel::validateFirstProperty($this->firstProperty))  {
+            if (!is_null($this->firstProperty)) {
+                return $this->firstProperty->to(); /*class*/
+            } else {
+                return  null;
+            }
+        }
+        throw new Exception('never get to this TopLevel::firstProperty');
+    }
+
+    /**
+     * @param MyObject|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateFirstProperty(?MyObject $value): bool {
+        if (!is_null($value)) {
+            $value->validate();
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return ?MyObject
+     */
+    public function getFirstProperty(): ?MyObject {
+        if (TopLevel::validateFirstProperty($this->firstProperty))  {
+            return $this->firstProperty;
+        }
+        throw new Exception('never get to getFirstProperty TopLevel::firstProperty');
+    }
+
+    /**
+     * @return ?MyObject
+     */
+    public static function sampleFirstProperty(): ?MyObject {
+        return MyObject::sample(); /*31:firstProperty*/
+    }
+
+    /**
+     * @param stdClass|array|null $value
+     * @throws Exception
+     * @return MyObjectB|array|null
+     */
+    public static function fromSecondProperty(stdClass|array|null $value): MyObjectB|array|null {
+        if (is_null($value)) {
+            return $value; /*null*/
+        } elseif (is_object($value)) {
+            return MyObjectB::from($value); /*class*/
+        } elseif (is_array($value)) {
+            return  array_map(function ($value) {
+                return MyObjectA::from($value); /*class*/
+            }, $value);
+        } else {
+            throw new Exception('Cannot deserialize union value in TopLevel');
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return stdClass|array|null
+     */
+    public function toSecondProperty(): stdClass|array|null {
+        if (TopLevel::validateSecondProperty($this->secondProperty))  {
+            if (is_null($this->secondProperty)) {
+                return $this->secondProperty; /*null*/
+            } elseif ($this->secondProperty instanceof MyObjectB) {
+                return $this->secondProperty->to(); /*class*/
+            } elseif (is_array($this->secondProperty)) {
+                return array_map(function ($value) {
+                    return $value->to(); /*class*/
+                }, $this->secondProperty);
+            } else {
+                throw new Exception('Union value has no matching member in TopLevel');
+            }
+        }
+        throw new Exception('never get to this TopLevel::secondProperty');
+    }
+
+    /**
+     * @param MyObjectB|array|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateSecondProperty(MyObjectB|array|null $value): bool {
+        if (is_null($value)) {
+            if (!is_null($value)) {
+                throw new Exception("Attribute Error:TopLevel::secondProperty");
+            }
+        } elseif ($value instanceof MyObjectB) {
+            $value->validate();
+        } elseif (is_array($value)) {
+            if (!is_array($value)) {
+                throw new Exception("Attribute Error:TopLevel::secondProperty");
+            }
+            array_walk($value, function($value_v) {
+                $value_v->validate();
+            });
+        } else {
+            throw new Exception("Attribute Error:TopLevel::secondProperty");
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return MyObjectB|array|null
+     */
+    public function getSecondProperty(): MyObjectB|array|null {
+        if (TopLevel::validateSecondProperty($this->secondProperty))  {
+            return $this->secondProperty;
+        }
+        throw new Exception('never get to getSecondProperty TopLevel::secondProperty');
+    }
+
+    /**
+     * @return MyObjectB|array|null
+     */
+    public static function sampleSecondProperty(): MyObjectB|array|null {
+        return MyObjectB::sample(); /*32:secondProperty*/
+    }
+
+    /**
+     * @throws Exception
+     * @return bool
+     */
+    public function validate(): bool {
+        return TopLevel::validateFirstProperty($this->firstProperty)
+        || TopLevel::validateSecondProperty($this->secondProperty);
+    }
+
+    /**
+     * @return stdClass
+     * @throws Exception
+     */
+    public function to(): stdClass  {
+        $out = new stdClass();
+        $out->{'firstProperty'} = $this->toFirstProperty();
+        $out->{'secondProperty'} = $this->toSecondProperty();
+        return $out;
+    }
+
+    /**
+     * @param stdClass $obj
+     * @return TopLevel
+     * @throws Exception
+     */
+    public static function from(stdClass $obj): TopLevel {
+        return new TopLevel(
+         TopLevel::fromFirstProperty($obj->{'firstProperty'})
+        ,TopLevel::fromSecondProperty($obj->{'secondProperty'})
+        );
+    }
+
+    /**
+     * @return TopLevel
+     */
+    public static function sample(): TopLevel {
+        return new TopLevel(
+         TopLevel::sampleFirstProperty()
+        ,TopLevel::sampleSecondProperty()
+        );
+    }
+}
+
+// This is an autogenerated file:MyObject
+
+class MyObject {
+    private ?string $a; // json:a Optional
+    private ?float $b; // json:b Optional
+    private ?bool $c; // json:c Optional
+    private ?string $d; // json:d Optional
+    private ?float $e; // json:e Optional
+    private ?bool $f; // json:f Optional
+
+    /**
+     * @param string|null $a
+     * @param float|null $b
+     * @param bool|null $c
+     * @param string|null $d
+     * @param float|null $e
+     * @param bool|null $f
+     */
+    public function __construct(?string $a, ?float $b, ?bool $c, ?string $d, ?float $e, ?bool $f) {
+        $this->a = $a;
+        $this->b = $b;
+        $this->c = $c;
+        $this->d = $d;
+        $this->e = $e;
+        $this->f = $f;
+    }
+
+    /**
+     * @param ?string $value
+     * @throws Exception
+     * @return ?string
+     */
+    public static function fromA(?string $value): ?string {
+        if (!is_null($value)) {
+            return $value; /*string*/
+        } else {
+            return  null;
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return ?string
+     */
+    public function toA(): ?string {
+        if (MyObject::validateA($this->a))  {
+            if (!is_null($this->a)) {
+                return $this->a; /*string*/
+            } else {
+                return  null;
+            }
+        }
+        throw new Exception('never get to this MyObject::a');
+    }
+
+    /**
+     * @param string|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateA(?string $value): bool {
+        if (!is_null($value)) {
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return ?string
+     */
+    public function getA(): ?string {
+        if (MyObject::validateA($this->a))  {
+            return $this->a;
+        }
+        throw new Exception('never get to getA MyObject::a');
+    }
+
+    /**
+     * @return ?string
+     */
+    public static function sampleA(): ?string {
+        return 'MyObject::a::31'; /*31:a*/
+    }
+
+    /**
+     * @param ?float $value
+     * @throws Exception
+     * @return ?float
+     */
+    public static function fromB(?float $value): ?float {
+        if (!is_null($value)) {
+            return $value; /*float*/
+        } else {
+            return  null;
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return ?float
+     */
+    public function toB(): ?float {
+        if (MyObject::validateB($this->b))  {
+            if (!is_null($this->b)) {
+                return $this->b; /*float*/
+            } else {
+                return  null;
+            }
+        }
+        throw new Exception('never get to this MyObject::b');
+    }
+
+    /**
+     * @param float|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateB(?float $value): bool {
+        if (!is_null($value)) {
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return ?float
+     */
+    public function getB(): ?float {
+        if (MyObject::validateB($this->b))  {
+            return $this->b;
+        }
+        throw new Exception('never get to getB MyObject::b');
+    }
+
+    /**
+     * @return ?float
+     */
+    public static function sampleB(): ?float {
+        return 32.032; /*32:b*/
+    }
+
+    /**
+     * @param ?bool $value
+     * @throws Exception
+     * @return ?bool
+     */
+    public static function fromC(?bool $value): ?bool {
+        if (!is_null($value)) {
+            return $value; /*bool*/
+        } else {
+            return  null;
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return ?bool
+     */
+    public function toC(): ?bool {
+        if (MyObject::validateC($this->c))  {
+            if (!is_null($this->c)) {
+                return $this->c; /*bool*/
+            } else {
+                return  null;
+            }
+        }
+        throw new Exception('never get to this MyObject::c');
+    }
+
+    /**
+     * @param bool|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateC(?bool $value): bool {
+        if (!is_null($value)) {
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return ?bool
+     */
+    public function getC(): ?bool {
+        if (MyObject::validateC($this->c))  {
+            return $this->c;
+        }
+        throw new Exception('never get to getC MyObject::c');
+    }
+
+    /**
+     * @return ?bool
+     */
+    public static function sampleC(): ?bool {
+        return true; /*33:c*/
+    }
+
+    /**
+     * @param ?string $value
+     * @throws Exception
+     * @return ?string
+     */
+    public static function fromD(?string $value): ?string {
+        if (!is_null($value)) {
+            return $value; /*string*/
+        } else {
+            return  null;
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return ?string
+     */
+    public function toD(): ?string {
+        if (MyObject::validateD($this->d))  {
+            if (!is_null($this->d)) {
+                return $this->d; /*string*/
+            } else {
+                return  null;
+            }
+        }
+        throw new Exception('never get to this MyObject::d');
+    }
+
+    /**
+     * @param string|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateD(?string $value): bool {
+        if (!is_null($value)) {
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return ?string
+     */
+    public function getD(): ?string {
+        if (MyObject::validateD($this->d))  {
+            return $this->d;
+        }
+        throw new Exception('never get to getD MyObject::d');
+    }
+
+    /**
+     * @return ?string
+     */
+    public static function sampleD(): ?string {
+        return 'MyObject::d::34'; /*34:d*/
+    }
+
+    /**
+     * @param ?float $value
+     * @throws Exception
+     * @return ?float
+     */
+    public static function fromE(?float $value): ?float {
+        if (!is_null($value)) {
+            return $value; /*float*/
+        } else {
+            return  null;
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return ?float
+     */
+    public function toE(): ?float {
+        if (MyObject::validateE($this->e))  {
+            if (!is_null($this->e)) {
+                return $this->e; /*float*/
+            } else {
+                return  null;
+            }
+        }
+        throw new Exception('never get to this MyObject::e');
+    }
+
+    /**
+     * @param float|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateE(?float $value): bool {
+        if (!is_null($value)) {
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return ?float
+     */
+    public function getE(): ?float {
+        if (MyObject::validateE($this->e))  {
+            return $this->e;
+        }
+        throw new Exception('never get to getE MyObject::e');
+    }
+
+    /**
+     * @return ?float
+     */
+    public static function sampleE(): ?float {
+        return 35.035; /*35:e*/
+    }
+
+    /**
+     * @param ?bool $value
+     * @throws Exception
+     * @return ?bool
+     */
+    public static function fromF(?bool $value): ?bool {
+        if (!is_null($value)) {
+            return $value; /*bool*/
+        } else {
+            return  null;
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return ?bool
+     */
+    public function toF(): ?bool {
+        if (MyObject::validateF($this->f))  {
+            if (!is_null($this->f)) {
+                return $this->f; /*bool*/
+            } else {
+                return  null;
+            }
+        }
+        throw new Exception('never get to this MyObject::f');
+    }
+
+    /**
+     * @param bool|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateF(?bool $value): bool {
+        if (!is_null($value)) {
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return ?bool
+     */
+    public function getF(): ?bool {
+        if (MyObject::validateF($this->f))  {
+            return $this->f;
+        }
+        throw new Exception('never get to getF MyObject::f');
+    }
+
+    /**
+     * @return ?bool
+     */
+    public static function sampleF(): ?bool {
+        return true; /*36:f*/
+    }
+
+    /**
+     * @throws Exception
+     * @return bool
+     */
+    public function validate(): bool {
+        return MyObject::validateA($this->a)
+        || MyObject::validateB($this->b)
+        || MyObject::validateC($this->c)
+        || MyObject::validateD($this->d)
+        || MyObject::validateE($this->e)
+        || MyObject::validateF($this->f);
+    }
+
+    /**
+     * @return stdClass
+     * @throws Exception
+     */
+    public function to(): stdClass  {
+        $out = new stdClass();
+        $out->{'a'} = $this->toA();
+        $out->{'b'} = $this->toB();
+        $out->{'c'} = $this->toC();
+        $out->{'d'} = $this->toD();
+        $out->{'e'} = $this->toE();
+        $out->{'f'} = $this->toF();
+        return $out;
+    }
+
+    /**
+     * @param stdClass $obj
+     * @return MyObject
+     * @throws Exception
+     */
+    public static function from(stdClass $obj): MyObject {
+        return new MyObject(
+         MyObject::fromA($obj->{'a'})
+        ,MyObject::fromB($obj->{'b'})
+        ,MyObject::fromC($obj->{'c'})
+        ,MyObject::fromD($obj->{'d'})
+        ,MyObject::fromE($obj->{'e'})
+        ,MyObject::fromF($obj->{'f'})
+        );
+    }
+
+    /**
+     * @return MyObject
+     */
+    public static function sample(): MyObject {
+        return new MyObject(
+         MyObject::sampleA()
+        ,MyObject::sampleB()
+        ,MyObject::sampleC()
+        ,MyObject::sampleD()
+        ,MyObject::sampleE()
+        ,MyObject::sampleF()
+        );
+    }
+}
+
+// This is an autogenerated file:MyObjectA
+
+class MyObjectA {
+    private ?string $a; // json:a Optional
+    private ?float $b; // json:b Optional
+    private ?bool $c; // json:c Optional
+
+    /**
+     * @param string|null $a
+     * @param float|null $b
+     * @param bool|null $c
+     */
+    public function __construct(?string $a, ?float $b, ?bool $c) {
+        $this->a = $a;
+        $this->b = $b;
+        $this->c = $c;
+    }
+
+    /**
+     * @param ?string $value
+     * @throws Exception
+     * @return ?string
+     */
+    public static function fromA(?string $value): ?string {
+        if (!is_null($value)) {
+            return $value; /*string*/
+        } else {
+            return  null;
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return ?string
+     */
+    public function toA(): ?string {
+        if (MyObjectA::validateA($this->a))  {
+            if (!is_null($this->a)) {
+                return $this->a; /*string*/
+            } else {
+                return  null;
+            }
+        }
+        throw new Exception('never get to this MyObjectA::a');
+    }
+
+    /**
+     * @param string|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateA(?string $value): bool {
+        if (!is_null($value)) {
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return ?string
+     */
+    public function getA(): ?string {
+        if (MyObjectA::validateA($this->a))  {
+            return $this->a;
+        }
+        throw new Exception('never get to getA MyObjectA::a');
+    }
+
+    /**
+     * @return ?string
+     */
+    public static function sampleA(): ?string {
+        return 'MyObjectA::a::31'; /*31:a*/
+    }
+
+    /**
+     * @param ?float $value
+     * @throws Exception
+     * @return ?float
+     */
+    public static function fromB(?float $value): ?float {
+        if (!is_null($value)) {
+            return $value; /*float*/
+        } else {
+            return  null;
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return ?float
+     */
+    public function toB(): ?float {
+        if (MyObjectA::validateB($this->b))  {
+            if (!is_null($this->b)) {
+                return $this->b; /*float*/
+            } else {
+                return  null;
+            }
+        }
+        throw new Exception('never get to this MyObjectA::b');
+    }
+
+    /**
+     * @param float|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateB(?float $value): bool {
+        if (!is_null($value)) {
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return ?float
+     */
+    public function getB(): ?float {
+        if (MyObjectA::validateB($this->b))  {
+            return $this->b;
+        }
+        throw new Exception('never get to getB MyObjectA::b');
+    }
+
+    /**
+     * @return ?float
+     */
+    public static function sampleB(): ?float {
+        return 32.032; /*32:b*/
+    }
+
+    /**
+     * @param ?bool $value
+     * @throws Exception
+     * @return ?bool
+     */
+    public static function fromC(?bool $value): ?bool {
+        if (!is_null($value)) {
+            return $value; /*bool*/
+        } else {
+            return  null;
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return ?bool
+     */
+    public function toC(): ?bool {
+        if (MyObjectA::validateC($this->c))  {
+            if (!is_null($this->c)) {
+                return $this->c; /*bool*/
+            } else {
+                return  null;
+            }
+        }
+        throw new Exception('never get to this MyObjectA::c');
+    }
+
+    /**
+     * @param bool|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateC(?bool $value): bool {
+        if (!is_null($value)) {
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return ?bool
+     */
+    public function getC(): ?bool {
+        if (MyObjectA::validateC($this->c))  {
+            return $this->c;
+        }
+        throw new Exception('never get to getC MyObjectA::c');
+    }
+
+    /**
+     * @return ?bool
+     */
+    public static function sampleC(): ?bool {
+        return true; /*33:c*/
+    }
+
+    /**
+     * @throws Exception
+     * @return bool
+     */
+    public function validate(): bool {
+        return MyObjectA::validateA($this->a)
+        || MyObjectA::validateB($this->b)
+        || MyObjectA::validateC($this->c);
+    }
+
+    /**
+     * @return stdClass
+     * @throws Exception
+     */
+    public function to(): stdClass  {
+        $out = new stdClass();
+        $out->{'a'} = $this->toA();
+        $out->{'b'} = $this->toB();
+        $out->{'c'} = $this->toC();
+        return $out;
+    }
+
+    /**
+     * @param stdClass $obj
+     * @return MyObjectA
+     * @throws Exception
+     */
+    public static function from(stdClass $obj): MyObjectA {
+        return new MyObjectA(
+         MyObjectA::fromA($obj->{'a'})
+        ,MyObjectA::fromB($obj->{'b'})
+        ,MyObjectA::fromC($obj->{'c'})
+        );
+    }
+
+    /**
+     * @return MyObjectA
+     */
+    public static function sample(): MyObjectA {
+        return new MyObjectA(
+         MyObjectA::sampleA()
+        ,MyObjectA::sampleB()
+        ,MyObjectA::sampleC()
+        );
+    }
+}
+
+// This is an autogenerated file:MyObjectB
+
+class MyObjectB {
+    private ?string $d; // json:d Optional
+    private ?float $e; // json:e Optional
+    private ?bool $f; // json:f Optional
+
+    /**
+     * @param string|null $d
+     * @param float|null $e
+     * @param bool|null $f
+     */
+    public function __construct(?string $d, ?float $e, ?bool $f) {
+        $this->d = $d;
+        $this->e = $e;
+        $this->f = $f;
+    }
+
+    /**
+     * @param ?string $value
+     * @throws Exception
+     * @return ?string
+     */
+    public static function fromD(?string $value): ?string {
+        if (!is_null($value)) {
+            return $value; /*string*/
+        } else {
+            return  null;
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return ?string
+     */
+    public function toD(): ?string {
+        if (MyObjectB::validateD($this->d))  {
+            if (!is_null($this->d)) {
+                return $this->d; /*string*/
+            } else {
+                return  null;
+            }
+        }
+        throw new Exception('never get to this MyObjectB::d');
+    }
+
+    /**
+     * @param string|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateD(?string $value): bool {
+        if (!is_null($value)) {
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return ?string
+     */
+    public function getD(): ?string {
+        if (MyObjectB::validateD($this->d))  {
+            return $this->d;
+        }
+        throw new Exception('never get to getD MyObjectB::d');
+    }
+
+    /**
+     * @return ?string
+     */
+    public static function sampleD(): ?string {
+        return 'MyObjectB::d::31'; /*31:d*/
+    }
+
+    /**
+     * @param ?float $value
+     * @throws Exception
+     * @return ?float
+     */
+    public static function fromE(?float $value): ?float {
+        if (!is_null($value)) {
+            return $value; /*float*/
+        } else {
+            return  null;
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return ?float
+     */
+    public function toE(): ?float {
+        if (MyObjectB::validateE($this->e))  {
+            if (!is_null($this->e)) {
+                return $this->e; /*float*/
+            } else {
+                return  null;
+            }
+        }
+        throw new Exception('never get to this MyObjectB::e');
+    }
+
+    /**
+     * @param float|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateE(?float $value): bool {
+        if (!is_null($value)) {
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return ?float
+     */
+    public function getE(): ?float {
+        if (MyObjectB::validateE($this->e))  {
+            return $this->e;
+        }
+        throw new Exception('never get to getE MyObjectB::e');
+    }
+
+    /**
+     * @return ?float
+     */
+    public static function sampleE(): ?float {
+        return 32.032; /*32:e*/
+    }
+
+    /**
+     * @param ?bool $value
+     * @throws Exception
+     * @return ?bool
+     */
+    public static function fromF(?bool $value): ?bool {
+        if (!is_null($value)) {
+            return $value; /*bool*/
+        } else {
+            return  null;
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return ?bool
+     */
+    public function toF(): ?bool {
+        if (MyObjectB::validateF($this->f))  {
+            if (!is_null($this->f)) {
+                return $this->f; /*bool*/
+            } else {
+                return  null;
+            }
+        }
+        throw new Exception('never get to this MyObjectB::f');
+    }
+
+    /**
+     * @param bool|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateF(?bool $value): bool {
+        if (!is_null($value)) {
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return ?bool
+     */
+    public function getF(): ?bool {
+        if (MyObjectB::validateF($this->f))  {
+            return $this->f;
+        }
+        throw new Exception('never get to getF MyObjectB::f');
+    }
+
+    /**
+     * @return ?bool
+     */
+    public static function sampleF(): ?bool {
+        return true; /*33:f*/
+    }
+
+    /**
+     * @throws Exception
+     * @return bool
+     */
+    public function validate(): bool {
+        return MyObjectB::validateD($this->d)
+        || MyObjectB::validateE($this->e)
+        || MyObjectB::validateF($this->f);
+    }
+
+    /**
+     * @return stdClass
+     * @throws Exception
+     */
+    public function to(): stdClass  {
+        $out = new stdClass();
+        $out->{'d'} = $this->toD();
+        $out->{'e'} = $this->toE();
+        $out->{'f'} = $this->toF();
+        return $out;
+    }
+
+    /**
+     * @param stdClass $obj
+     * @return MyObjectB
+     * @throws Exception
+     */
+    public static function from(stdClass $obj): MyObjectB {
+        return new MyObjectB(
+         MyObjectB::fromD($obj->{'d'})
+        ,MyObjectB::fromE($obj->{'e'})
+        ,MyObjectB::fromF($obj->{'f'})
+        );
+    }
+
+    /**
+     * @return MyObjectB
+     */
+    public static function sample(): MyObjectB {
+        return new MyObjectB(
+         MyObjectB::sampleD()
+        ,MyObjectB::sampleE()
+        ,MyObjectB::sampleF()
+        );
+    }
+}
diff --git a/head/schema-pike/test/inputs/schema/anyof-object-union.schema/default/TopLevel.pmod b/head/schema-pike/test/inputs/schema/anyof-object-union.schema/default/TopLevel.pmod
new file mode 100644
index 0000000..ba3863d
--- /dev/null
+++ b/head/schema-pike/test/inputs/schema/anyof-object-union.schema/default/TopLevel.pmod
@@ -0,0 +1,129 @@
+// This source has been automatically generated by quicktype.
+// ( https://github.com/quicktype/quicktype )
+//
+// To use this code, simply import it into your project as a Pike module.
+// To JSON-encode your object, you can pass it to `Standards.JSON.encode`
+// or call `encode_json` on it.
+//
+// To decode a JSON string, first pass it to `Standards.JSON.decode`,
+// and then pass the result to `<YourClass>_from_JSON`.
+// It will return an instance of <YourClass>.
+// Bear in mind that these functions have unexpected behavior,
+// and will likely throw an error, if the JSON string does not
+// match the expected interface, even if the JSON itself is valid.
+
+class TopLevel {
+    MyObject|mixed first_property;  // json: "firstProperty"
+    SecondProperty second_property; // json: "secondProperty"
+
+    string encode_json() {
+        mapping(string:mixed) json = ([
+            "firstProperty" : first_property,
+            "secondProperty" : second_property,
+        ]);
+
+        return Standards.JSON.encode(json);
+    }
+}
+
+TopLevel TopLevel_from_JSON(mixed json) {
+    TopLevel retval = TopLevel();
+
+    retval.first_property = json["firstProperty"];
+    retval.second_property = json["secondProperty"];
+
+    return retval;
+}
+
+class MyObject {
+    mixed|string a; // json: "a"
+    float|mixed  b; // json: "b"
+    bool|mixed   c; // json: "c"
+    mixed|string d; // json: "d"
+    float|mixed  e; // json: "e"
+    bool|mixed   f; // json: "f"
+
+    string encode_json() {
+        mapping(string:mixed) json = ([
+            "a" : a,
+            "b" : b,
+            "c" : c,
+            "d" : d,
+            "e" : e,
+            "f" : f,
+        ]);
+
+        return Standards.JSON.encode(json);
+    }
+}
+
+MyObject MyObject_from_JSON(mixed json) {
+    MyObject retval = MyObject();
+
+    retval.a = json["a"];
+    retval.b = json["b"];
+    retval.c = json["c"];
+    retval.d = json["d"];
+    retval.e = json["e"];
+    retval.f = json["f"];
+
+    return retval;
+}
+
+typedef array(MyObjectA)|MyObjectB SecondProperty;
+
+SecondProperty SecondProperty_from_JSON(mixed json) {
+    return json;
+}
+
+class MyObjectA {
+    mixed|string a; // json: "a"
+    float|mixed  b; // json: "b"
+    bool|mixed   c; // json: "c"
+
+    string encode_json() {
+        mapping(string:mixed) json = ([
+            "a" : a,
+            "b" : b,
+            "c" : c,
+        ]);
+
+        return Standards.JSON.encode(json);
+    }
+}
+
+MyObjectA MyObjectA_from_JSON(mixed json) {
+    MyObjectA retval = MyObjectA();
+
+    retval.a = json["a"];
+    retval.b = json["b"];
+    retval.c = json["c"];
+
+    return retval;
+}
+
+class MyObjectB {
+    mixed|string d; // json: "d"
+    float|mixed  e; // json: "e"
+    bool|mixed   f; // json: "f"
+
+    string encode_json() {
+        mapping(string:mixed) json = ([
+            "d" : d,
+            "e" : e,
+            "f" : f,
+        ]);
+
+        return Standards.JSON.encode(json);
+    }
+}
+
+MyObjectB MyObjectB_from_JSON(mixed json) {
+    MyObjectB retval = MyObjectB();
+
+    retval.d = json["d"];
+    retval.e = json["e"];
+    retval.f = json["f"];
+
+    return retval;
+}
diff --git a/head/schema-python/test/inputs/schema/anyof-object-union.schema/default/quicktype.py b/head/schema-python/test/inputs/schema/anyof-object-union.schema/default/quicktype.py
new file mode 100644
index 0000000..7cc1a12
--- /dev/null
+++ b/head/schema-python/test/inputs/schema/anyof-object-union.schema/default/quicktype.py
@@ -0,0 +1,165 @@
+from dataclasses import dataclass
+from typing import Any, TypeVar, Callable, Type, cast
+
+
+T = TypeVar("T")
+
+
+def from_str(x: Any) -> str:
+    assert isinstance(x, str)
+    return x
+
+
+def from_none(x: Any) -> Any:
+    assert x is None
+    return x
+
+
+def from_union(fs, x):
+    for f in fs:
+        try:
+            return f(x)
+        except:
+            pass
+    assert False
+
+
+def from_float(x: Any) -> float:
+    assert isinstance(x, (float, int)) and not isinstance(x, bool)
+    return float(x)
+
+
+def from_bool(x: Any) -> bool:
+    assert isinstance(x, bool)
+    return x
+
+
+def to_float(x: Any) -> float:
+    assert isinstance(x, (int, float))
+    return x
+
+
+def from_list(f: Callable[[Any], T], x: Any) -> list[T]:
+    assert isinstance(x, list)
+    return [f(y) for y in x]
+
+
+def to_class(c: Type[T], x: Any) -> dict:
+    assert isinstance(x, c)
+    return cast(Any, x).to_dict()
+
+
+@dataclass
+class MyObject:
+    a: str | None = None
+    b: float | None = None
+    c: bool | None = None
+    d: str | None = None
+    e: float | None = None
+    f: bool | None = None
+
+    @staticmethod
+    def from_dict(obj: Any) -> 'MyObject':
+        assert isinstance(obj, dict)
+        a = from_union([from_str, from_none], obj.get("a"))
+        b = from_union([from_float, from_none], obj.get("b"))
+        c = from_union([from_bool, from_none], obj.get("c"))
+        d = from_union([from_str, from_none], obj.get("d"))
+        e = from_union([from_float, from_none], obj.get("e"))
+        f = from_union([from_bool, from_none], obj.get("f"))
+        return MyObject(a, b, c, d, e, f)
+
+    def to_dict(self) -> dict:
+        result: dict = {}
+        if self.a is not None:
+            result["a"] = from_union([from_str, from_none], self.a)
+        if self.b is not None:
+            result["b"] = from_union([to_float, from_none], self.b)
+        if self.c is not None:
+            result["c"] = from_union([from_bool, from_none], self.c)
+        if self.d is not None:
+            result["d"] = from_union([from_str, from_none], self.d)
+        if self.e is not None:
+            result["e"] = from_union([to_float, from_none], self.e)
+        if self.f is not None:
+            result["f"] = from_union([from_bool, from_none], self.f)
+        return result
+
+
+@dataclass
+class MyObjectA:
+    a: str | None = None
+    b: float | None = None
+    c: bool | None = None
+
+    @staticmethod
+    def from_dict(obj: Any) -> 'MyObjectA':
+        assert isinstance(obj, dict)
+        a = from_union([from_str, from_none], obj.get("a"))
+        b = from_union([from_float, from_none], obj.get("b"))
+        c = from_union([from_bool, from_none], obj.get("c"))
+        return MyObjectA(a, b, c)
+
+    def to_dict(self) -> dict:
+        result: dict = {}
+        if self.a is not None:
+            result["a"] = from_union([from_str, from_none], self.a)
+        if self.b is not None:
+            result["b"] = from_union([to_float, from_none], self.b)
+        if self.c is not None:
+            result["c"] = from_union([from_bool, from_none], self.c)
+        return result
+
+
+@dataclass
+class MyObjectB:
+    d: str | None = None
+    e: float | None = None
+    f: bool | None = None
+
+    @staticmethod
+    def from_dict(obj: Any) -> 'MyObjectB':
+        assert isinstance(obj, dict)
+        d = from_union([from_str, from_none], obj.get("d"))
+        e = from_union([from_float, from_none], obj.get("e"))
+        f = from_union([from_bool, from_none], obj.get("f"))
+        return MyObjectB(d, e, f)
+
+    def to_dict(self) -> dict:
+        result: dict = {}
+        if self.d is not None:
+            result["d"] = from_union([from_str, from_none], self.d)
+        if self.e is not None:
+            result["e"] = from_union([to_float, from_none], self.e)
+        if self.f is not None:
+            result["f"] = from_union([from_bool, from_none], self.f)
+        return result
+
+
+@dataclass
+class TopLevel:
+    first_property: MyObject | None = None
+    second_property: list[MyObjectA] | MyObjectB | None = None
+
+    @staticmethod
+    def from_dict(obj: Any) -> 'TopLevel':
+        assert isinstance(obj, dict)
+        first_property = from_union([MyObject.from_dict, from_none], obj.get("firstProperty"))
+        second_property = from_union([lambda x: from_list(MyObjectA.from_dict, x), MyObjectB.from_dict, from_none], obj.get("secondProperty"))
+        return TopLevel(first_property, second_property)
+
+    def to_dict(self) -> dict:
+        result: dict = {}
+        if self.first_property is not None:
+            result["firstProperty"] = from_union([lambda x: to_class(MyObject, x), from_none], self.first_property)
+        if self.second_property is not None:
+            result["secondProperty"] = from_union([lambda x: from_list(lambda x: to_class(MyObjectA, x), x), lambda x: to_class(MyObjectB, x), from_none], self.second_property)
+        return result
+
+
+def top_level_from_dict(s: Any) -> TopLevel:
+    return TopLevel.from_dict(s)
+
+
+def top_level_to_dict(x: TopLevel) -> Any:
+    return to_class(TopLevel, x)
diff --git a/head/schema-ruby/test/inputs/schema/anyof-object-union.schema/default/TopLevel.rb b/head/schema-ruby/test/inputs/schema/anyof-object-union.schema/default/TopLevel.rb
new file mode 100644
index 0000000..629c9d8
--- /dev/null
+++ b/head/schema-ruby/test/inputs/schema/anyof-object-union.schema/default/TopLevel.rb
@@ -0,0 +1,191 @@
+# This code may look unusually verbose for Ruby (and it is), but
+# it performs some subtle and complex validation of JSON data.
+#
+# To parse this JSON, add 'dry-struct' and 'dry-types' gems, then do:
+#
+#   top_level = TopLevel.from_json! "{…}"
+#   puts top_level.first_property&.a
+#
+# If from_json! succeeds, the value returned matches the schema.
+
+require 'json'
+require 'dry-types'
+require 'dry-struct'
+
+module Types
+  include Dry.Types(default: :nominal)
+
+  Bool   = Strict::Bool
+  Hash   = Strict::Hash
+  String = Strict::String
+  Double = Strict::Float | Strict::Integer
+end
+
+class MyObject < Dry::Struct
+  attribute :a, Types::String.optional
+  attribute :b, Types::Double.optional
+  attribute :c, Types::Bool.optional
+  attribute :d, Types::String.optional
+  attribute :e, Types::Double.optional
+  attribute :f, Types::Bool.optional
+
+  def self.from_dynamic!(d)
+    d = Types::Hash[d]
+    new(
+      a: d["a"],
+      b: d["b"],
+      c: d["c"],
+      d: d["d"],
+      e: d["e"],
+      f: d["f"],
+    )
+  end
+
+  def self.from_json!(json)
+    from_dynamic!(JSON.parse(json))
+  end
+
+  def to_dynamic
+    {
+      "a" => a,
+      "b" => b,
+      "c" => c,
+      "d" => d,
+      "e" => e,
+      "f" => f,
+    }
+  end
+
+  def to_json(options = nil)
+    JSON.generate(to_dynamic, options)
+  end
+end
+
+class MyObjectA < Dry::Struct
+  attribute :a, Types::String.optional
+  attribute :b, Types::Double.optional
+  attribute :c, Types::Bool.optional
+
+  def self.from_dynamic!(d)
+    d = Types::Hash[d]
+    new(
+      a: d["a"],
+      b: d["b"],
+      c: d["c"],
+    )
+  end
+
+  def self.from_json!(json)
+    from_dynamic!(JSON.parse(json))
+  end
+
+  def to_dynamic
+    {
+      "a" => a,
+      "b" => b,
+      "c" => c,
+    }
+  end
+
+  def to_json(options = nil)
+    JSON.generate(to_dynamic, options)
+  end
+end
+
+class MyObjectB < Dry::Struct
+  attribute :d, Types::String.optional
+  attribute :e, Types::Double.optional
+  attribute :f, Types::Bool.optional
+
+  def self.from_dynamic!(d)
+    d = Types::Hash[d]
+    new(
+      d: d["d"],
+      e: d["e"],
+      f: d["f"],
+    )
+  end
+
+  def self.from_json!(json)
+    from_dynamic!(JSON.parse(json))
+  end
+
+  def to_dynamic
+    {
+      "d" => d,
+      "e" => e,
+      "f" => f,
+    }
+  end
+
+  def to_json(options = nil)
+    JSON.generate(to_dynamic, options)
+  end
+end
+
+class SecondProperty < Dry::Struct
+  attribute :my_object_a_array, Types.Array(MyObjectA).optional
+  attribute :my_object_b,       MyObjectB.optional
+
+  def self.from_dynamic!(d)
+    begin
+      value = d.map { |x| MyObjectA.from_dynamic!(x) }
+      if schema[:my_object_a_array].right.valid? value
+        return new(my_object_a_array: value, my_object_b: nil)
+      end
+    rescue
+    end
+    begin
+      value = MyObjectB.from_dynamic!(d)
+      if schema[:my_object_b].right.valid? value
+        return new(my_object_b: value, my_object_a_array: nil)
+      end
+    rescue
+    end
+    raise "Invalid union"
+  end
+
+  def self.from_json!(json)
+    from_dynamic!(JSON.parse(json))
+  end
+
+  def to_dynamic
+    if my_object_a_array != nil
+      my_object_a_array.map { |x| x.to_dynamic }
+    elsif my_object_b != nil
+      my_object_b.to_dynamic
+    end
+  end
+
+  def to_json(options = nil)
+    JSON.generate(to_dynamic, options)
+  end
+end
+
+class TopLevel < Dry::Struct
+  attribute :first_property,  MyObject.optional
+  attribute :second_property, Types.Instance(SecondProperty).optional
+
+  def self.from_dynamic!(d)
+    d = Types::Hash[d]
+    new(
+      first_property:  d["firstProperty"] ? MyObject.from_dynamic!(d["firstProperty"]) : nil,
+      second_property: d["secondProperty"] ? SecondProperty.from_dynamic!(d["secondProperty"]) : nil,
+    )
+  end
+
+  def self.from_json!(json)
+    from_dynamic!(JSON.parse(json))
+  end
+
+  def to_dynamic
+    {
+      "firstProperty"  => first_property&.to_dynamic,
+      "secondProperty" => second_property&.to_dynamic,
+    }
+  end
+
+  def to_json(options = nil)
+    JSON.generate(to_dynamic, options)
+  end
+end
diff --git a/head/schema-rust/test/inputs/schema/anyof-object-union.schema/default/module_under_test.rs b/head/schema-rust/test/inputs/schema/anyof-object-union.schema/default/module_under_test.rs
new file mode 100644
index 0000000..6b3ef0b
--- /dev/null
+++ b/head/schema-rust/test/inputs/schema/anyof-object-union.schema/default/module_under_test.rs
@@ -0,0 +1,63 @@
+// Example code that deserializes and serializes the model.
+// extern crate serde;
+// #[macro_use]
+// extern crate serde_derive;
+// extern crate serde_json;
+//
+// use generated_module::TopLevel;
+//
+// fn main() {
+//     let json = r#"{"answer": 42}"#;
+//     let model: TopLevel = serde_json::from_str(&json).unwrap();
+// }
+
+use serde::{Serialize, Deserialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TopLevel {
+    pub first_property: Option<MyObject>,
+
+    pub second_property: Option<SecondProperty>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MyObject {
+    pub a: Option<String>,
+
+    pub b: Option<f64>,
+
+    pub c: Option<bool>,
+
+    pub d: Option<String>,
+
+    pub e: Option<f64>,
+
+    pub f: Option<bool>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(untagged)]
+pub enum SecondProperty {
+    MyObjectAArray(Vec<MyObjectA>),
+
+    MyObjectB(MyObjectB),
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MyObjectA {
+    pub a: Option<String>,
+
+    pub b: Option<f64>,
+
+    pub c: Option<bool>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MyObjectB {
+    pub d: Option<String>,
+
+    pub e: Option<f64>,
+
+    pub f: Option<bool>,
+}
diff --git a/head/schema-scala3/test/inputs/schema/anyof-object-union.schema/default/TopLevel.scala b/head/schema-scala3/test/inputs/schema/anyof-object-union.schema/default/TopLevel.scala
new file mode 100644
index 0000000..8429053
--- /dev/null
+++ b/head/schema-scala3/test/inputs/schema/anyof-object-union.schema/default/TopLevel.scala
@@ -0,0 +1,47 @@
+package quicktype
+
+import io.circe.syntax._
+import io.circe._
+import cats.syntax.functor._
+
+// If a union has a null in, then we'll need this too... 
+type NullValue = None.type
+
+case class TopLevel (
+    val firstProperty : Option[MyObject] = None,
+    val secondProperty : Option[SecondProperty] = None
+) derives Encoder.AsObject, Decoder
+
+case class MyObject (
+    val a : Option[String] = None,
+    val b : Option[Double] = None,
+    val c : Option[Boolean] = None,
+    val d : Option[String] = None,
+    val e : Option[Double] = None,
+    val f : Option[Boolean] = None
+) derives Encoder.AsObject, Decoder
+
+type SecondProperty = Seq[MyObjectA] | MyObjectB
+given Decoder[SecondProperty] = {
+    List[Decoder[SecondProperty]](
+        Decoder[Seq[MyObjectA]].widen,
+        Decoder[MyObjectB].widen,
+    ).reduceLeft(_ or _)
+}
+
+given Encoder[SecondProperty] = Encoder.instance {
+    case enc0 : Seq[MyObjectA] => Encoder.encodeSeq[MyObjectA].apply(enc0)
+    case enc1 : MyObjectB => Encoder.AsObject[MyObjectB].apply(enc1)
+}
+
+case class MyObjectA (
+    val a : Option[String] = None,
+    val b : Option[Double] = None,
+    val c : Option[Boolean] = None
+) derives Encoder.AsObject, Decoder
+
+case class MyObjectB (
+    val d : Option[String] = None,
+    val e : Option[Double] = None,
+    val f : Option[Boolean] = None
+) derives Encoder.AsObject, Decoder
diff --git a/head/schema-scala3-upickle/test/inputs/schema/anyof-object-union.schema/default/TopLevel.scala b/head/schema-scala3-upickle/test/inputs/schema/anyof-object-union.schema/default/TopLevel.scala
new file mode 100644
index 0000000..4af80da
--- /dev/null
+++ b/head/schema-scala3-upickle/test/inputs/schema/anyof-object-union.schema/default/TopLevel.scala
@@ -0,0 +1,104 @@
+package quicktype
+
+// Custom pickler so that missing keys and JSON nulls both read as None,
+// and None is left out when writing (upickle's default for Option is a
+// JSON array).
+object OptionPickler extends upickle.AttributeTagged:
+    import upickle.default.Writer
+    import upickle.default.Reader
+    override implicit def OptionWriter[T: Writer]: Writer[Option[T]] =
+        implicitly[Writer[T]].comap[Option[T]] {
+            case None => null.asInstanceOf[T]
+            case Some(x) => x
+        }
+
+    override implicit def OptionReader[T: Reader]: Reader[Option[T]] = {
+        new Reader.Delegate[Any, Option[T]](implicitly[Reader[T]].map(Some(_))){
+        override def visitNull(index: Int) = None
+        }
+    }
+end OptionPickler
+
+// If a union has a null in, then we'll need this too...
+type NullValue = None.type
+given OptionPickler.ReadWriter[NullValue] = OptionPickler.readwriter[ujson.Value].bimap[NullValue](
+    _ => ujson.Null,
+    json => if json.isNull then None else throw new upickle.core.Abort("not null")
+)
+
+object JsonExt:
+    val valueReader = OptionPickler.readwriter[ujson.Value]
+
+    // upickle's built-in primitive readers are lenient -- the numeric and
+    // boolean readers accept strings, and the string reader accepts
+    // numbers and booleans -- so untagged unions need strict readers to
+    // pick the right member.
+    val strictString: OptionPickler.Reader[String] = valueReader.map {
+        case ujson.Str(s) => s
+        case json => throw new upickle.core.Abort("expected string, got " + json)
+    }
+    val strictLong: OptionPickler.Reader[Long] = valueReader.map {
+        case ujson.Num(n) if n.isWhole => n.toLong
+        case json => throw new upickle.core.Abort("expected integer, got " + json)
+    }
+    val strictDouble: OptionPickler.Reader[Double] = valueReader.map {
+        case ujson.Num(n) => n
+        case json => throw new upickle.core.Abort("expected number, got " + json)
+    }
+    val strictBoolean: OptionPickler.Reader[Boolean] = valueReader.map {
+        case ujson.Bool(b) => b
+        case json => throw new upickle.core.Abort("expected boolean, got " + json)
+    }
+
+    def badMerge[T](r1: => OptionPickler.Reader[?], rest: OptionPickler.Reader[?]*): OptionPickler.Reader[T] = valueReader.map { json =>
+        var t: T | Null = null
+        val stack       = Vector.newBuilder[Throwable]
+        (r1 +: rest).foreach { reader =>
+            if t == null then
+            try
+                t = OptionPickler.read[T](json, trace = true)(using reader.asInstanceOf[OptionPickler.Reader[T]])
+            catch
+                case exc => stack += exc
+        }
+        if t != null then t.nn else throw new Exception(json.toString(), stack.result().headOption.getOrElse(null))
+    }
+end JsonExt
+
+
+case class TopLevel (
+    val firstProperty : Option[MyObject] = None,
+    val secondProperty : Option[SecondProperty] = None
+) derives OptionPickler.ReadWriter
+
+case class MyObject (
+    val a : Option[String] = None,
+    val b : Option[Double] = None,
+    val c : Option[Boolean] = None,
+    val d : Option[String] = None,
+    val e : Option[Double] = None,
+    val f : Option[Boolean] = None
+) derives OptionPickler.ReadWriter
+
+type SecondProperty = Seq[MyObjectA] | MyObjectB
+given unionReaderSecondProperty: OptionPickler.Reader[SecondProperty] = JsonExt.badMerge[SecondProperty](
+    summon[OptionPickler.Reader[Seq[MyObjectA]]],
+    summon[OptionPickler.Reader[MyObjectB]],
+    )
+
+given unionWriterSecondProperty: OptionPickler.Writer[SecondProperty] = OptionPickler.writer[ujson.Value].comap[SecondProperty]{ _v =>
+    (_v: @unchecked) match 
+        case v: Seq[MyObjectA] => OptionPickler.writeJs[Seq[MyObjectA]](v)
+        case v: MyObjectB => OptionPickler.writeJs[MyObjectB](v)
+}
+
+case class MyObjectA (
+    val a : Option[String] = None,
+    val b : Option[Double] = None,
+    val c : Option[Boolean] = None
+) derives OptionPickler.ReadWriter
+
+case class MyObjectB (
+    val d : Option[String] = None,
+    val e : Option[Double] = None,
+    val f : Option[Boolean] = None
+) derives OptionPickler.ReadWriter
diff --git a/head/schema-schema/test/inputs/schema/anyof-object-union.schema/default/TopLevel.schema b/head/schema-schema/test/inputs/schema/anyof-object-union.schema/default/TopLevel.schema
new file mode 100644
index 0000000..13868c9
--- /dev/null
+++ b/head/schema-schema/test/inputs/schema/anyof-object-union.schema/default/TopLevel.schema
@@ -0,0 +1,94 @@
+{
+    "$schema": "http://json-schema.org/draft-06/schema#",
+    "$ref": "#/definitions/TopLevel",
+    "definitions": {
+        "TopLevel": {
+            "type": "object",
+            "additionalProperties": false,
+            "properties": {
+                "firstProperty": {
+                    "$ref": "#/definitions/MyObject"
+                },
+                "secondProperty": {
+                    "$ref": "#/definitions/SecondProperty"
+                }
+            },
+            "required": [],
+            "title": "TopLevel"
+        },
+        "MyObject": {
+            "type": "object",
+            "additionalProperties": false,
+            "properties": {
+                "a": {
+                    "type": "string"
+                },
+                "b": {
+                    "type": "number"
+                },
+                "c": {
+                    "type": "boolean"
+                },
+                "d": {
+                    "type": "string"
+                },
+                "e": {
+                    "type": "number"
+                },
+                "f": {
+                    "type": "boolean"
+                }
+            },
+            "required": [],
+            "title": "MyObject"
+        },
+        "MyObjectA": {
+            "type": "object",
+            "additionalProperties": false,
+            "properties": {
+                "a": {
+                    "type": "string"
+                },
+                "b": {
+                    "type": "number"
+                },
+                "c": {
+                    "type": "boolean"
+                }
+            },
+            "required": [],
+            "title": "MyObjectA"
+        },
+        "MyObjectB": {
+            "type": "object",
+            "additionalProperties": false,
+            "properties": {
+                "d": {
+                    "type": "string"
+                },
+                "e": {
+                    "type": "number"
+                },
+                "f": {
+                    "type": "boolean"
+                }
+            },
+            "required": [],
+            "title": "MyObjectB"
+        },
+        "SecondProperty": {
+            "anyOf": [
+                {
+                    "type": "array",
+                    "items": {
+                        "$ref": "#/definitions/MyObjectA"
+                    }
+                },
+                {
+                    "$ref": "#/definitions/MyObjectB"
+                }
+            ],
+            "title": "SecondProperty"
+        }
+    }
+}
diff --git a/head/schema-swift/test/inputs/schema/anyof-object-union.schema/default/quicktype.swift b/head/schema-swift/test/inputs/schema/anyof-object-union.schema/default/quicktype.swift
new file mode 100644
index 0000000..e9c7e6a
--- /dev/null
+++ b/head/schema-swift/test/inputs/schema/anyof-object-union.schema/default/quicktype.swift
@@ -0,0 +1,286 @@
+// This file was generated from JSON Schema using quicktype, do not modify it directly.
+// To parse the JSON, add this file to your project and do:
+//
+//   let topLevel = try TopLevel(json)
+
+import Foundation
+
+// MARK: - TopLevel
+struct TopLevel: Codable {
+    let firstProperty: MyObject?
+    let secondProperty: SecondProperty?
+
+    enum CodingKeys: String, CodingKey {
+        case firstProperty = "firstProperty"
+        case secondProperty = "secondProperty"
+    }
+}
+
+// MARK: TopLevel convenience initializers and mutators
+
+extension TopLevel {
+    init(data: Data) throws {
+        self = try newJSONDecoder().decode(TopLevel.self, from: data)
+    }
+
+    init(_ json: String, using encoding: String.Encoding = .utf8) throws {
+        guard let data = json.data(using: encoding) else {
+            throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
+        }
+        try self.init(data: data)
+    }
+
+    init(fromURL url: URL) throws {
+        try self.init(data: try Data(contentsOf: url))
+    }
+
+    func with(
+        firstProperty: MyObject?? = nil,
+        secondProperty: SecondProperty?? = nil
+    ) -> TopLevel {
+        return TopLevel(
+            firstProperty: firstProperty ?? self.firstProperty,
+            secondProperty: secondProperty ?? self.secondProperty
+        )
+    }
+
+    func jsonData() throws -> Data {
+        return try newJSONEncoder().encode(self)
+    }
+
+    func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
+        return String(data: try self.jsonData(), encoding: encoding)
+    }
+}
+
+// MARK: - MyObject
+struct MyObject: Codable {
+    let a: String?
+    let b: Double?
+    let c: Bool?
+    let d: String?
+    let e: Double?
+    let f: Bool?
+
+    enum CodingKeys: String, CodingKey {
+        case a = "a"
+        case b = "b"
+        case c = "c"
+        case d = "d"
+        case e = "e"
+        case f = "f"
+    }
+}
+
+// MARK: MyObject convenience initializers and mutators
+
+extension MyObject {
+    init(data: Data) throws {
+        self = try newJSONDecoder().decode(MyObject.self, from: data)
+    }
+
+    init(_ json: String, using encoding: String.Encoding = .utf8) throws {
+        guard let data = json.data(using: encoding) else {
+            throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
+        }
+        try self.init(data: data)
+    }
+
+    init(fromURL url: URL) throws {
+        try self.init(data: try Data(contentsOf: url))
+    }
+
+    func with(
+        a: String?? = nil,
+        b: Double?? = nil,
+        c: Bool?? = nil,
+        d: String?? = nil,
+        e: Double?? = nil,
+        f: Bool?? = nil
+    ) -> MyObject {
+        return MyObject(
+            a: a ?? self.a,
+            b: b ?? self.b,
+            c: c ?? self.c,
+            d: d ?? self.d,
+            e: e ?? self.e,
+            f: f ?? self.f
+        )
+    }
+
+    func jsonData() throws -> Data {
+        return try newJSONEncoder().encode(self)
+    }
+
+    func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
+        return String(data: try self.jsonData(), encoding: encoding)
+    }
+}
+
+enum SecondProperty: Codable {
+    case myObjectAArray([MyObjectA])
+    case myObjectB(MyObjectB)
+
+    init(from decoder: Decoder) throws {
+        let container = try decoder.singleValueContainer()
+        if let x = try? container.decode([MyObjectA].self) {
+            self = .myObjectAArray(x)
+            return
+        }
+        if let x = try? container.decode(MyObjectB.self) {
+            self = .myObjectB(x)
+            return
+        }
+        throw DecodingError.typeMismatch(SecondProperty.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for SecondProperty"))
+    }
+
+    func encode(to encoder: Encoder) throws {
+        var container = encoder.singleValueContainer()
+        switch self {
+        case .myObjectAArray(let x):
+            try container.encode(x)
+        case .myObjectB(let x):
+            try container.encode(x)
+        }
+    }
+}
+
+// MARK: - MyObjectA
+struct MyObjectA: Codable {
+    let a: String?
+    let b: Double?
+    let c: Bool?
+
+    enum CodingKeys: String, CodingKey {
+        case a = "a"
+        case b = "b"
+        case c = "c"
+    }
+}
+
+// MARK: MyObjectA convenience initializers and mutators
+
+extension MyObjectA {
+    init(data: Data) throws {
+        self = try newJSONDecoder().decode(MyObjectA.self, from: data)
+    }
+
+    init(_ json: String, using encoding: String.Encoding = .utf8) throws {
+        guard let data = json.data(using: encoding) else {
+            throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
+        }
+        try self.init(data: data)
+    }
+
+    init(fromURL url: URL) throws {
+        try self.init(data: try Data(contentsOf: url))
+    }
+
+    func with(
+        a: String?? = nil,
+        b: Double?? = nil,
+        c: Bool?? = nil
+    ) -> MyObjectA {
+        return MyObjectA(
+            a: a ?? self.a,
+            b: b ?? self.b,
+            c: c ?? self.c
+        )
+    }
+
+    func jsonData() throws -> Data {
+        return try newJSONEncoder().encode(self)
+    }
+
+    func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
+        return String(data: try self.jsonData(), encoding: encoding)
+    }
+}
+
+// MARK: - MyObjectB
+struct MyObjectB: Codable {
+    let d: String?
+    let e: Double?
+    let f: Bool?
+
+    enum CodingKeys: String, CodingKey {
+        case d = "d"
+        case e = "e"
+        case f = "f"
+    }
+}
+
+// MARK: MyObjectB convenience initializers and mutators
+
+extension MyObjectB {
+    init(data: Data) throws {
+        self = try newJSONDecoder().decode(MyObjectB.self, from: data)
+    }
+
+    init(_ json: String, using encoding: String.Encoding = .utf8) throws {
+        guard let data = json.data(using: encoding) else {
+            throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
+        }
+        try self.init(data: data)
+    }
+
+    init(fromURL url: URL) throws {
+        try self.init(data: try Data(contentsOf: url))
+    }
+
+    func with(
+        d: String?? = nil,
+        e: Double?? = nil,
+        f: Bool?? = nil
+    ) -> MyObjectB {
+        return MyObjectB(
+            d: d ?? self.d,
+            e: e ?? self.e,
+            f: f ?? self.f
+        )
+    }
+
+    func jsonData() throws -> Data {
+        return try newJSONEncoder().encode(self)
+    }
+
+    func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
+        return String(data: try self.jsonData(), encoding: encoding)
+    }
+}
+
+// MARK: - Helper functions for creating encoders and decoders
+
+func newJSONDecoder() -> JSONDecoder {
+    let decoder = JSONDecoder()
+    decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in
+        let container = try decoder.singleValueContainer()
+        let dateStr = try container.decode(String.self)
+
+        let formatter = DateFormatter()
+        formatter.calendar = Calendar(identifier: .iso8601)
+        formatter.locale = Locale(identifier: "en_US_POSIX")
+        formatter.timeZone = TimeZone(secondsFromGMT: 0)
+        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
+        if let date = formatter.date(from: dateStr) {
+            return date
+        }
+        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
+        if let date = formatter.date(from: dateStr) {
+            return date
+        }
+        throw DecodingError.typeMismatch(Date.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not decode date"))
+    })
+    return decoder
+}
+
+func newJSONEncoder() -> JSONEncoder {
+    let encoder = JSONEncoder()
+    let formatter = DateFormatter()
+    formatter.calendar = Calendar(identifier: .iso8601)
+    formatter.locale = Locale(identifier: "en_US_POSIX")
+    formatter.timeZone = TimeZone(secondsFromGMT: 0)
+    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
+    encoder.dateEncodingStrategy = .formatted(formatter)
+    return encoder
+}
diff --git a/head/schema-typescript/test/inputs/schema/anyof-object-union.schema/default/TopLevel.ts b/head/schema-typescript/test/inputs/schema/anyof-object-union.schema/default/TopLevel.ts
new file mode 100644
index 0000000..5988fb4
--- /dev/null
+++ b/head/schema-typescript/test/inputs/schema/anyof-object-union.schema/default/TopLevel.ts
@@ -0,0 +1,211 @@
+// To parse this data:
+//
+//   import { Convert, TopLevel } from "./TopLevel";
+//
+//   const topLevel = Convert.toTopLevel(json);
+//
+// These functions will throw an error if the JSON doesn't
+// match the expected interface, even if the JSON is valid.
+
+export interface TopLevel {
+    firstProperty?:  FirstProperty;
+    secondProperty?: SecondProperty;
+}
+
+export type FirstProperty = MyObjectA | MyObjectB;
+
+export interface MyObjectA {
+    a?: string;
+    b?: number;
+    c?: boolean;
+}
+
+export interface MyObjectB {
+    d?: string;
+    e?: number;
+    f?: boolean;
+}
+
+export type SecondProperty = MyObjectA[] | MyObjectB;
+
+// Converts JSON strings to/from your types
+// and asserts the results of JSON.parse at runtime
+export class Convert {
+    public static toTopLevel(json: string): TopLevel {
+        return cast(JSON.parse(json), r("TopLevel"));
+    }
+
+    public static topLevelToJson(value: TopLevel): string {
+        return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
+    }
+}
+
+function invalidValue(typ: any, val: any, key: any, parent: any = ''): never {
+    const prettyTyp = prettyTypeName(typ);
+    const parentText = parent ? ` on ${parent}` : '';
+    const keyText = key ? ` for key "${key}"` : '';
+    throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
+}
+
+function prettyTypeName(typ: any): string {
+    if (Array.isArray(typ)) {
+        if (typ.length === 2 && typ[0] === undefined) {
+            return `an optional ${prettyTypeName(typ[1])}`;
+        } else {
+            return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
+        }
+    } else if (typeof typ === "object" && typ.literal !== undefined) {
+        return typ.literal;
+    } else {
+        return typeof typ;
+    }
+}
+
+function jsonToJSProps(typ: any): any {
+    if (typ.jsonToJS === undefined) {
+        const map: any = {};
+        typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
+        typ.jsonToJS = map;
+    }
+    return typ.jsonToJS;
+}
+
+function jsToJSONProps(typ: any): any {
+    if (typ.jsToJSON === undefined) {
+        const map: any = {};
+        typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
+        typ.jsToJSON = map;
+    }
+    return typ.jsToJSON;
+}
+
+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
+    function transformPrimitive(typ: string, val: any): any {
+        if (typeof typ === typeof val) return val;
+        return invalidValue(typ, val, key, parent);
+    }
+
+    function transformUnion(typs: any[], val: any): any {
+        // val must validate against one typ in typs
+        const l = typs.length;
+        for (let i = 0; i < l; i++) {
+            const typ = typs[i];
+            try {
+                return transform(val, typ, getProps);
+            } catch (_) {}
+        }
+        return invalidValue(typs, val, key, parent);
+    }
+
+    function transformEnum(cases: string[], val: any): any {
+        if (cases.indexOf(val) !== -1) return val;
+        return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
+    }
+
+    function transformArray(typ: any, val: any): any {
+        // val must be an array with no invalid elements
+        if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
+        return val.map(el => transform(el, typ, getProps));
+    }
+
+    function transformDate(val: any): any {
+        if (val === null) {
+            return null;
+        }
+        const d = new Date(val);
+        if (isNaN(d.valueOf())) {
+            return invalidValue(l("Date"), val, key, parent);
+        }
+        return d;
+    }
+
+    function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
+        if (val === null || typeof val !== "object" || Array.isArray(val)) {
+            return invalidValue(l(ref || "object"), val, key, parent);
+        }
+        const result: any = {};
+        Object.getOwnPropertyNames(props).forEach(key => {
+            const prop = props[key];
+            const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
+            result[prop.key] = transform(v, prop.typ, getProps, key, ref);
+        });
+        Object.getOwnPropertyNames(val).forEach(key => {
+            if (!Object.prototype.hasOwnProperty.call(props, key)) {
+                result[key] = transform(val[key], additional, getProps, key, ref);
+            }
+        });
+        return result;
+    }
+
+    if (typ === "any") return val;
+    if (typ === null) {
+        if (val === null) return val;
+        return invalidValue(typ, val, key, parent);
+    }
+    if (typ === false) return invalidValue(typ, val, key, parent);
+    let ref: any = undefined;
+    while (typeof typ === "object" && typ.ref !== undefined) {
+        ref = typ.ref;
+        typ = typeMap[typ.ref];
+    }
+    if (Array.isArray(typ)) return transformEnum(typ, val);
+    if (typeof typ === "object") {
+        return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
+            : typ.hasOwnProperty("arrayItems")    ? transformArray(typ.arrayItems, val)
+            : typ.hasOwnProperty("props")         ? transformObject(getProps(typ), typ.additional, val)
+            : invalidValue(typ, val, key, parent);
+    }
+    // Numbers can be parsed by Date but shouldn't be.
+    if (typ === Date && typeof val !== "number") return transformDate(val);
+    return transformPrimitive(typ, val);
+}
+
+function cast<T>(val: any, typ: any): T {
+    return transform(val, typ, jsonToJSProps);
+}
+
+function uncast<T>(val: T, typ: any): any {
+    return transform(val, typ, jsToJSONProps);
+}
+
+function l(typ: any) {
+    return { literal: typ };
+}
+
+function a(typ: any) {
+    return { arrayItems: typ };
+}
+
+function u(...typs: any[]) {
+    return { unionMembers: typs };
+}
+
+function o(props: any[], additional: any) {
+    return { props, additional };
+}
+
+function m(additional: any) {
+    const props: any[] = [];
+    return { props, additional };
+}
+
+function r(name: string) {
+    return { ref: name };
+}
+
+const typeMap: any = {
+    "TopLevel": o([
+        { json: "firstProperty", js: "firstProperty", typ: u(undefined, u(r("MyObjectA"), r("MyObjectB"))) },
+        { json: "secondProperty", js: "secondProperty", typ: u(undefined, u(a(r("MyObjectA")), r("MyObjectB"))) },
+    ], false),
+    "MyObjectA": o([
+        { json: "a", js: "a", typ: u(undefined, "") },
+        { json: "b", js: "b", typ: u(undefined, 3.14) },
+        { json: "c", js: "c", typ: u(undefined, true) },
+    ], false),
+    "MyObjectB": o([
+        { json: "d", js: "d", typ: u(undefined, "") },
+        { json: "e", js: "e", typ: u(undefined, 3.14) },
+        { json: "f", js: "f", typ: u(undefined, true) },
+    ], false),
+};
diff --git a/base/schema-typescript/test/inputs/schema/nested-intersection-union.schema/default/TopLevel.ts b/head/schema-typescript/test/inputs/schema/nested-intersection-union.schema/default/TopLevel.ts
index ead6805..03f23c2 100644
--- a/base/schema-typescript/test/inputs/schema/nested-intersection-union.schema/default/TopLevel.ts
+++ b/head/schema-typescript/test/inputs/schema/nested-intersection-union.schema/default/TopLevel.ts
@@ -8,14 +8,26 @@
 // match the expected interface, even if the JSON is valid.
 
 export interface TopLevel {
-    input: Item[];
+    input: Input[];
 }
 
-export interface Item {
-    content?: string;
-    id?:      string;
-    output?:  string;
-    summary?: string;
+export type Input = Message | Item;
+
+export interface Message {
+    content: string;
+    [property: string]: unknown;
+}
+
+export type Item = FunctionOutput | ReasoningItem;
+
+export interface FunctionOutput {
+    id:     string;
+    output: string;
+    [property: string]: unknown;
+}
+
+export interface ReasoningItem {
+    summary: string;
     [property: string]: unknown;
 }
 
@@ -186,12 +198,16 @@ function r(name: string) {
 
 const typeMap: any = {
     "TopLevel": o([
-        { json: "input", js: "input", typ: a(r("Item")) },
+        { json: "input", js: "input", typ: a(u(r("Message"), u(r("FunctionOutput"), r("ReasoningItem")))) },
     ], false),
-    "Item": o([
-        { json: "content", js: "content", typ: u(undefined, "") },
-        { json: "id", js: "id", typ: u(undefined, "") },
-        { json: "output", js: "output", typ: u(undefined, "") },
-        { json: "summary", js: "summary", typ: u(undefined, "") },
+    "Message": o([
+        { json: "content", js: "content", typ: "" },
+    ], "any"),
+    "FunctionOutput": o([
+        { json: "id", js: "id", typ: "" },
+        { json: "output", js: "output", typ: "" },
+    ], "any"),
+    "ReasoningItem": o([
+        { json: "summary", js: "summary", typ: "" },
     ], "any"),
 };
diff --git a/base/schema-typescript/test/inputs/schema/nullable-optional-one-of.schema/default/TopLevel.ts b/head/schema-typescript/test/inputs/schema/nullable-optional-one-of.schema/default/TopLevel.ts
index b5c10df..4a5881d 100644
--- a/base/schema-typescript/test/inputs/schema/nullable-optional-one-of.schema/default/TopLevel.ts
+++ b/head/schema-typescript/test/inputs/schema/nullable-optional-one-of.schema/default/TopLevel.ts
@@ -7,23 +7,33 @@
 // These functions will throw an error if the JSON doesn't
 // match the expected interface, even if the JSON is valid.
 
-export interface TopLevel {
+export type TopLevel = One | Two;
+
+export interface One {
+    b:    null | string;
+    kind: PurpleKind;
+    [property: string]: unknown;
+}
+
+export type PurpleKind = "one";
+
+export interface Two {
     b?:   null | string;
-    kind: Kind;
+    kind: FluffyKind;
     [property: string]: unknown;
 }
 
-export type Kind = "one" | "two";
+export type FluffyKind = "two";
 
 // Converts JSON strings to/from your types
 // and asserts the results of JSON.parse at runtime
 export class Convert {
     public static toTopLevel(json: string): TopLevel {
-        return cast(JSON.parse(json), r("TopLevel"));
+        return cast(JSON.parse(json), u(r("One"), r("Two")));
     }
 
     public static topLevelToJson(value: TopLevel): string {
-        return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
+        return JSON.stringify(uncast(value, u(r("One"), r("Two"))), null, 2);
     }
 }
 
@@ -181,12 +191,18 @@ function r(name: string) {
 }
 
 const typeMap: any = {
-    "TopLevel": o([
+    "One": o([
+        { json: "b", js: "b", typ: u(null, "") },
+        { json: "kind", js: "kind", typ: r("PurpleKind") },
+    ], "any"),
+    "Two": o([
         { json: "b", js: "b", typ: u(undefined, u(null, "")) },
-        { json: "kind", js: "kind", typ: r("Kind") },
+        { json: "kind", js: "kind", typ: r("FluffyKind") },
     ], "any"),
-    "Kind": [
+    "PurpleKind": [
         "one",
+    ],
+    "FluffyKind": [
         "two",
     ],
 };
diff --git a/base/schema-typescript/test/inputs/schema/postman-collection.schema/default/TopLevel.ts b/head/schema-typescript/test/inputs/schema/postman-collection.schema/default/TopLevel.ts
index 6a5d984..2c7017d 100644
--- a/base/schema-typescript/test/inputs/schema/postman-collection.schema/default/TopLevel.ts
+++ b/head/schema-typescript/test/inputs/schema/postman-collection.schema/default/TopLevel.ts
@@ -7,11 +7,17 @@
 // These functions will throw an error if the JSON doesn't
 // match the expected interface, even if the JSON is valid.
 
+export interface Group {
+    item?: TopLevel[];
+    [property: string]: unknown;
+}
+
 /**
  * Postman collection
  */
-export interface TopLevel {
-    item?:     TopLevel[];
+export type TopLevel = Group | Item;
+
+export interface Item {
     name?:     string;
     response?: Response[];
     [property: string]: unknown;
@@ -26,11 +32,11 @@ export interface Response {
 // and asserts the results of JSON.parse at runtime
 export class Convert {
     public static toTopLevel(json: string): TopLevel {
-        return cast(JSON.parse(json), r("TopLevel"));
+        return cast(JSON.parse(json), u(r("Group"), r("Item")));
     }
 
     public static topLevelToJson(value: TopLevel): string {
-        return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
+        return JSON.stringify(uncast(value, u(r("Group"), r("Item"))), null, 2);
     }
 }
 
@@ -188,8 +194,10 @@ function r(name: string) {
 }
 
 const typeMap: any = {
-    "TopLevel": o([
-        { json: "item", js: "item", typ: u(undefined, a(r("TopLevel"))) },
+    "Group": o([
+        { json: "item", js: "item", typ: u(undefined, a(u(r("Group"), r("Item")))) },
+    ], "any"),
+    "Item": o([
         { json: "name", js: "name", typ: u(undefined, "") },
         { json: "response", js: "response", typ: u(undefined, a(r("Response"))) },
     ], "any"),
diff --git a/head/schema-typescript-zod/test/inputs/schema/anyof-object-union.schema/default/TopLevel.ts b/head/schema-typescript-zod/test/inputs/schema/anyof-object-union.schema/default/TopLevel.ts
new file mode 100644
index 0000000..da0f386
--- /dev/null
+++ b/head/schema-typescript-zod/test/inputs/schema/anyof-object-union.schema/default/TopLevel.ts
@@ -0,0 +1,32 @@
+import * as z from "zod";
+
+
+export const MyObjectSchema = z.object({
+    "a": z.string().optional(),
+    "b": z.number().optional(),
+    "c": z.boolean().optional(),
+    "d": z.string().optional(),
+    "e": z.number().optional(),
+    "f": z.boolean().optional(),
+});
+export type MyObject = z.infer<typeof MyObjectSchema>;
+
+export const MyObjectASchema = z.object({
+    "a": z.string().optional(),
+    "b": z.number().optional(),
+    "c": z.boolean().optional(),
+});
+export type MyObjectA = z.infer<typeof MyObjectASchema>;
+
+export const MyObjectBSchema = z.object({
+    "d": z.string().optional(),
+    "e": z.number().optional(),
+    "f": z.boolean().optional(),
+});
+export type MyObjectB = z.infer<typeof MyObjectBSchema>;
+
+export const TopLevelSchema = z.object({
+    "firstProperty": MyObjectSchema.optional(),
+    "secondProperty": z.union([z.array(MyObjectASchema), MyObjectBSchema]).optional(),
+});
+export type TopLevel = z.infer<typeof TopLevelSchema>;
