diff --git a/head/schema-cplusplus/test/inputs/schema/recursive-ref-to-id.schema/default/quicktype.hpp b/head/schema-cplusplus/test/inputs/schema/recursive-ref-to-id.schema/default/quicktype.hpp
new file mode 100644
index 0000000..b62b524
--- /dev/null
+++ b/head/schema-cplusplus/test/inputs/schema/recursive-ref-to-id.schema/default/quicktype.hpp
@@ -0,0 +1,151 @@
+//  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 "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 Data {
+        public:
+        Data() = default;
+        virtual ~Data() = default;
+
+        private:
+        std::optional<std::string> id;
+
+        public:
+        const std::optional<std::string> & get_id() const { return id; }
+        std::optional<std::string> & get_mutable_id() { return id; }
+        void set_id(const std::optional<std::string> & value) { this->id = value; }
+    };
+
+    class TopLevel {
+        public:
+        TopLevel() = default;
+        virtual ~TopLevel() = default;
+
+        private:
+        std::optional<std::vector<TopLevel>> children;
+        std::optional<Data> data;
+
+        public:
+        const std::optional<std::vector<TopLevel>> & get_children() const { return children; }
+        std::optional<std::vector<TopLevel>> & get_mutable_children() { return children; }
+        void set_children(const std::optional<std::vector<TopLevel>> & value) { this->children = value; }
+
+        const std::optional<Data> & get_data() const { return data; }
+        std::optional<Data> & get_mutable_data() { return data; }
+        void set_data(const std::optional<Data> & value) { this->data = value; }
+    };
+}
+
+namespace quicktype {
+    void from_json(const json & j, Data & x);
+    void to_json(json & j, const Data & x);
+
+    void from_json(const json & j, TopLevel & x);
+    void to_json(json & j, const TopLevel & x);
+
+    inline void from_json(const json & j, Data& x) {
+        x.set_id(get_stack_optional<std::string>(j, "id"));
+    }
+
+    inline void to_json(json & j, const Data & x) {
+        j = json::object();
+        j["id"] = x.get_id();
+    }
+
+    inline void from_json(const json & j, TopLevel& x) {
+        x.set_children(get_stack_optional<std::vector<TopLevel>>(j, "children"));
+        x.set_data(get_stack_optional<Data>(j, "data"));
+    }
+
+    inline void to_json(json & j, const TopLevel & x) {
+        j = json::object();
+        j["children"] = x.get_children();
+        j["data"] = x.get_data();
+    }
+}
diff --git a/base/schema-cplusplus/test/inputs/schema/rust-cycle-breaker-union.schema/default/quicktype.hpp b/head/schema-cplusplus/test/inputs/schema/rust-cycle-breaker-union.schema/default/quicktype.hpp
index 01ae820..80960eb 100644
--- a/base/schema-cplusplus/test/inputs/schema/rust-cycle-breaker-union.schema/default/quicktype.hpp
+++ b/head/schema-cplusplus/test/inputs/schema/rust-cycle-breaker-union.schema/default/quicktype.hpp
@@ -89,27 +89,9 @@ namespace quicktype {
     }
     #endif
 
-    class Node;
+    class TopLevel;
 
-    using Next = std::shared_ptr<std::variant<std::shared_ptr<Node>, std::string>>;
-
-    class Node {
-        public:
-        Node() = default;
-        virtual ~Node() = default;
-
-        private:
-        Next next;
-        std::string value;
-
-        public:
-        Next get_next() const { return next; }
-        void set_next(Next value) { this->next = value; }
-
-        const std::string & get_value() const { return value; }
-        std::string & get_mutable_value() { return value; }
-        void set_value(const std::string & value) { this->value = value; }
-    };
+    using Next = std::optional<std::variant<std::shared_ptr<TopLevel>, std::string>>;
 
     class TopLevel {
         public:
@@ -131,33 +113,19 @@ namespace quicktype {
 }
 
 namespace quicktype {
-void from_json(const json & j, Node & x);
-void to_json(json & j, const Node & 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::shared_ptr<quicktype::Node>, std::string>> {
-    static void from_json(const json & j, std::variant<std::shared_ptr<quicktype::Node>, std::string> & x);
-    static void to_json(json & j, const std::variant<std::shared_ptr<quicktype::Node>, std::string> & x);
+struct adl_serializer<std::variant<std::shared_ptr<quicktype::TopLevel>, std::string>> {
+    static void from_json(const json & j, std::variant<std::shared_ptr<quicktype::TopLevel>, std::string> & x);
+    static void to_json(json & j, const std::variant<std::shared_ptr<quicktype::TopLevel>, std::string> & x);
 };
 }
 namespace quicktype {
-    inline void from_json(const json & j, Node& x) {
-        x.set_next(get_heap_optional<std::variant<std::shared_ptr<Node>, std::string>>(j, "next"));
-        x.set_value(j.at("value").get<std::string>());
-    }
-
-    inline void to_json(json & j, const Node & x) {
-        j = json::object();
-        j["next"] = x.get_next();
-        j["value"] = x.get_value();
-    }
-
     inline void from_json(const json & j, TopLevel& x) {
-        x.set_next(get_heap_optional<std::variant<std::shared_ptr<Node>, std::string>>(j, "next"));
+        x.set_next(get_stack_optional<std::variant<std::shared_ptr<TopLevel>, std::string>>(j, "next"));
         x.set_value(j.at("value").get<std::string>());
     }
 
@@ -168,18 +136,18 @@ namespace quicktype {
     }
 }
 namespace nlohmann {
-    inline void adl_serializer<std::variant<std::shared_ptr<quicktype::Node>, std::string>>::from_json(const json & j, std::variant<std::shared_ptr<quicktype::Node>, std::string> & x) {
+    inline void adl_serializer<std::variant<std::shared_ptr<quicktype::TopLevel>, std::string>>::from_json(const json & j, std::variant<std::shared_ptr<quicktype::TopLevel>, std::string> & x) {
         if (j.is_string())
             x = j.get<std::string>();
         else if (j.is_object())
-            x = j.get<std::shared_ptr<quicktype::Node>>();
+            x = j.get<std::shared_ptr<quicktype::TopLevel>>();
         else throw std::runtime_error("Could not deserialise!");
     }
 
-    inline void adl_serializer<std::variant<std::shared_ptr<quicktype::Node>, std::string>>::to_json(json & j, const std::variant<std::shared_ptr<quicktype::Node>, std::string> & x) {
+    inline void adl_serializer<std::variant<std::shared_ptr<quicktype::TopLevel>, std::string>>::to_json(json & j, const std::variant<std::shared_ptr<quicktype::TopLevel>, std::string> & x) {
         switch (x.index()) {
             case 0:
-                j = std::get<std::shared_ptr<quicktype::Node>>(x);
+                j = std::get<std::shared_ptr<quicktype::TopLevel>>(x);
                 break;
             case 1:
                 j = std::get<std::string>(x);
diff --git a/head/schema-csharp/test/inputs/schema/recursive-ref-to-id.schema/default/QuickType.cs b/head/schema-csharp/test/inputs/schema/recursive-ref-to-id.schema/default/QuickType.cs
new file mode 100644
index 0000000..8710b32
--- /dev/null
+++ b/head/schema-csharp/test/inputs/schema/recursive-ref-to-id.schema/default/QuickType.cs
@@ -0,0 +1,70 @@
+// <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("children", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public TopLevel[]? Children { get; set; }
+
+        [JsonProperty("data", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public Data? Data { get; set; }
+    }
+
+    public partial class Data
+    {
+        [JsonProperty("id", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public string? Id { get; set; }
+    }
+
+    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 =
+            {
+                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
+            },
+        };
+    }
+}
+#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/base/schema-csharp/test/inputs/schema/recursive-union-flattening.schema/default/QuickType.cs b/head/schema-csharp/test/inputs/schema/recursive-union-flattening.schema/default/QuickType.cs
index 8adf934..d605ed7 100644
--- a/base/schema-csharp/test/inputs/schema/recursive-union-flattening.schema/default/QuickType.cs
+++ b/head/schema-csharp/test/inputs/schema/recursive-union-flattening.schema/default/QuickType.cs
@@ -23,70 +23,46 @@ namespace QuickType
     using Newtonsoft.Json;
     using Newtonsoft.Json.Converters;
 
-    public partial class TopLevelClass
+    public partial class A
     {
         [JsonProperty("x")]
-        public X? X { get; set; }
+        public PurpleTopLevel? X { get; set; }
     }
 
-    public partial class XClass
-    {
-        [JsonProperty("x")]
-        public X? X { get; set; }
-    }
-
-    public partial struct X
-    {
-        public XElement[]? AnythingArray;
-        public Dictionary<string, object>? AnythingMap;
-        public bool? Bool;
-        public double? Double;
-        public long? Integer;
-        public string? String;
-
-        public static implicit operator X(XElement[] AnythingArray) => new X { AnythingArray = AnythingArray };
-        public static implicit operator X(Dictionary<string, object> AnythingMap) => new X { AnythingMap = AnythingMap };
-        public static implicit operator X(bool Bool) => new X { Bool = Bool };
-        public static implicit operator X(double Double) => new X { Double = Double };
-        public static implicit operator X(long Integer) => new X { Integer = Integer };
-        public static implicit operator X(string String) => new X { String = String };
-        public bool IsNull => AnythingArray == null && Bool == null && Double == null && Integer == null && AnythingMap == null && String == null;
-    }
-
-    public partial struct XElement
+    public partial struct TopLevelElement
     {
+        public A? A;
         public object[]? AnythingArray;
         public bool? Bool;
         public double? Double;
         public long? Integer;
         public string? String;
-        public XClass? XClass;
 
-        public static implicit operator XElement(object[] AnythingArray) => new XElement { AnythingArray = AnythingArray };
-        public static implicit operator XElement(bool Bool) => new XElement { Bool = Bool };
-        public static implicit operator XElement(double Double) => new XElement { Double = Double };
-        public static implicit operator XElement(long Integer) => new XElement { Integer = Integer };
-        public static implicit operator XElement(string String) => new XElement { String = String };
-        public static implicit operator XElement(XClass XClass) => new XElement { XClass = XClass };
-        public bool IsNull => AnythingArray == null && Bool == null && XClass == null && Double == null && Integer == null && String == null;
+        public static implicit operator TopLevelElement(A A) => new TopLevelElement { A = A };
+        public static implicit operator TopLevelElement(object[] AnythingArray) => new TopLevelElement { AnythingArray = AnythingArray };
+        public static implicit operator TopLevelElement(bool Bool) => new TopLevelElement { Bool = Bool };
+        public static implicit operator TopLevelElement(double Double) => new TopLevelElement { Double = Double };
+        public static implicit operator TopLevelElement(long Integer) => new TopLevelElement { Integer = Integer };
+        public static implicit operator TopLevelElement(string String) => new TopLevelElement { String = String };
+        public bool IsNull => AnythingArray == null && Bool == null && A == null && Double == null && Integer == null && String == null;
     }
 
-    public partial struct TopLevelElement
+    public partial struct PurpleTopLevel
     {
-        public object[]? AnythingArray;
+        public TopLevelElement[]? AnythingArray;
+        public Dictionary<string, object>? AnythingMap;
         public bool? Bool;
         public double? Double;
         public long? Integer;
         public string? String;
-        public TopLevelClass? TopLevelClass;
 
-        public static implicit operator TopLevelElement(object[] AnythingArray) => new TopLevelElement { AnythingArray = AnythingArray };
-        public static implicit operator TopLevelElement(bool Bool) => new TopLevelElement { Bool = Bool };
-        public static implicit operator TopLevelElement(double Double) => new TopLevelElement { Double = Double };
-        public static implicit operator TopLevelElement(long Integer) => new TopLevelElement { Integer = Integer };
-        public static implicit operator TopLevelElement(string String) => new TopLevelElement { String = String };
-        public static implicit operator TopLevelElement(TopLevelClass TopLevelClass) => new TopLevelElement { TopLevelClass = TopLevelClass };
-        public bool IsNull => AnythingArray == null && Bool == null && TopLevelClass == null && Double == null && Integer == null && String == null;
+        public static implicit operator PurpleTopLevel(TopLevelElement[] AnythingArray) => new PurpleTopLevel { AnythingArray = AnythingArray };
+        public static implicit operator PurpleTopLevel(Dictionary<string, object> AnythingMap) => new PurpleTopLevel { AnythingMap = AnythingMap };
+        public static implicit operator PurpleTopLevel(bool Bool) => new PurpleTopLevel { Bool = Bool };
+        public static implicit operator PurpleTopLevel(double Double) => new PurpleTopLevel { Double = Double };
+        public static implicit operator PurpleTopLevel(long Integer) => new PurpleTopLevel { Integer = Integer };
+        public static implicit operator PurpleTopLevel(string String) => new PurpleTopLevel { String = String };
+        public bool IsNull => AnythingArray == null && Bool == null && Double == null && Integer == null && AnythingMap == null && String == null;
     }
 
     public partial struct TopLevelUnion
@@ -127,8 +103,7 @@ namespace QuickType
             {
                 TopLevelUnionConverter.Singleton,
                 TopLevelElementConverter.Singleton,
-                XConverter.Singleton,
-                XElementConverter.Singleton,
+                PurpleTopLevelConverter.Singleton,
                 new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
             },
         };
@@ -235,8 +210,8 @@ namespace QuickType
                     var stringValue = serializer.Deserialize<string>(reader);
                     return new TopLevelElement { String = stringValue };
                 case JsonToken.StartObject:
-                    var objectValue = serializer.Deserialize<TopLevelClass>(reader);
-                    return new TopLevelElement { TopLevelClass = objectValue };
+                    var objectValue = serializer.Deserialize<A>(reader);
+                    return new TopLevelElement { A = objectValue };
                 case JsonToken.StartArray:
                     var arrayValue = serializer.Deserialize<object[]>(reader);
                     return new TopLevelElement { AnythingArray = arrayValue };
@@ -277,9 +252,9 @@ namespace QuickType
                 serializer.Serialize(writer, value.AnythingArray);
                 return;
             }
-            if (value.TopLevelClass != null)
+            if (value.A != null)
             {
-                serializer.Serialize(writer, value.TopLevelClass);
+                serializer.Serialize(writer, value.A);
                 return;
             }
             throw new Exception("Cannot marshal type TopLevelElement");
@@ -288,42 +263,42 @@ namespace QuickType
         public static readonly TopLevelElementConverter Singleton = new TopLevelElementConverter();
     }
 
-    internal class XConverter : JsonConverter
+    internal class PurpleTopLevelConverter : JsonConverter
     {
-        public override bool CanConvert(Type t) => t == typeof(X) || t == typeof(X?);
+        public override bool CanConvert(Type t) => t == typeof(PurpleTopLevel) || t == typeof(PurpleTopLevel?);
 
         public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
         {
             switch (reader.TokenType)
             {
                 case JsonToken.Null:
-                    return new X { };
+                    return new PurpleTopLevel { };
                 case JsonToken.Integer:
                     var integerValue = serializer.Deserialize<long>(reader);
-                    return new X { Integer = integerValue };
+                    return new PurpleTopLevel { Integer = integerValue };
                 case JsonToken.Float:
                     var doubleValue = serializer.Deserialize<double>(reader);
-                    return new X { Double = doubleValue };
+                    return new PurpleTopLevel { Double = doubleValue };
                 case JsonToken.Boolean:
                     var boolValue = serializer.Deserialize<bool>(reader);
-                    return new X { Bool = boolValue };
+                    return new PurpleTopLevel { Bool = boolValue };
                 case JsonToken.String:
                 case JsonToken.Date:
                     var stringValue = serializer.Deserialize<string>(reader);
-                    return new X { String = stringValue };
+                    return new PurpleTopLevel { String = stringValue };
                 case JsonToken.StartObject:
                     var objectValue = serializer.Deserialize<Dictionary<string, object>>(reader);
-                    return new X { AnythingMap = objectValue };
+                    return new PurpleTopLevel { AnythingMap = objectValue };
                 case JsonToken.StartArray:
-                    var arrayValue = serializer.Deserialize<XElement[]>(reader);
-                    return new X { AnythingArray = arrayValue };
+                    var arrayValue = serializer.Deserialize<TopLevelElement[]>(reader);
+                    return new PurpleTopLevel { AnythingArray = arrayValue };
             }
-            throw new Exception("Cannot unmarshal type X");
+            throw new Exception("Cannot unmarshal type PurpleTopLevel");
         }
 
         public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
         {
-            var value = (X)untypedValue;
+            var value = (PurpleTopLevel)untypedValue;
             if (value.IsNull)
             {
                 serializer.Serialize(writer, null);
@@ -359,87 +334,10 @@ namespace QuickType
                 serializer.Serialize(writer, value.AnythingMap);
                 return;
             }
-            throw new Exception("Cannot marshal type X");
-        }
-
-        public static readonly XConverter Singleton = new XConverter();
-    }
-
-    internal class XElementConverter : JsonConverter
-    {
-        public override bool CanConvert(Type t) => t == typeof(XElement) || t == typeof(XElement?);
-
-        public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
-        {
-            switch (reader.TokenType)
-            {
-                case JsonToken.Null:
-                    return new XElement { };
-                case JsonToken.Integer:
-                    var integerValue = serializer.Deserialize<long>(reader);
-                    return new XElement { Integer = integerValue };
-                case JsonToken.Float:
-                    var doubleValue = serializer.Deserialize<double>(reader);
-                    return new XElement { Double = doubleValue };
-                case JsonToken.Boolean:
-                    var boolValue = serializer.Deserialize<bool>(reader);
-                    return new XElement { Bool = boolValue };
-                case JsonToken.String:
-                case JsonToken.Date:
-                    var stringValue = serializer.Deserialize<string>(reader);
-                    return new XElement { String = stringValue };
-                case JsonToken.StartObject:
-                    var objectValue = serializer.Deserialize<XClass>(reader);
-                    return new XElement { XClass = objectValue };
-                case JsonToken.StartArray:
-                    var arrayValue = serializer.Deserialize<object[]>(reader);
-                    return new XElement { AnythingArray = arrayValue };
-            }
-            throw new Exception("Cannot unmarshal type XElement");
-        }
-
-        public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
-        {
-            var value = (XElement)untypedValue;
-            if (value.IsNull)
-            {
-                serializer.Serialize(writer, null);
-                return;
-            }
-            if (value.Integer != null)
-            {
-                serializer.Serialize(writer, value.Integer.Value);
-                return;
-            }
-            if (value.Double != null)
-            {
-                serializer.Serialize(writer, value.Double.Value);
-                return;
-            }
-            if (value.Bool != null)
-            {
-                serializer.Serialize(writer, value.Bool.Value);
-                return;
-            }
-            if (value.String != null)
-            {
-                serializer.Serialize(writer, value.String);
-                return;
-            }
-            if (value.AnythingArray != null)
-            {
-                serializer.Serialize(writer, value.AnythingArray);
-                return;
-            }
-            if (value.XClass != null)
-            {
-                serializer.Serialize(writer, value.XClass);
-                return;
-            }
-            throw new Exception("Cannot marshal type XElement");
+            throw new Exception("Cannot marshal type PurpleTopLevel");
         }
 
-        public static readonly XElementConverter Singleton = new XElementConverter();
+        public static readonly PurpleTopLevelConverter Singleton = new PurpleTopLevelConverter();
     }
 }
 #pragma warning restore CS8618
diff --git a/base/schema-csharp/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.cs b/head/schema-csharp/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.cs
index 76e2bac..82f46ac 100644
--- a/base/schema-csharp/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.cs
+++ b/head/schema-csharp/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.cs
@@ -32,23 +32,14 @@ namespace QuickType
         public string Value { get; set; }
     }
 
-    public partial class Node
-    {
-        [JsonProperty("next")]
-        public Next? Next { get; set; }
-
-        [JsonProperty("value", Required = Required.Always)]
-        public string Value { get; set; }
-    }
-
     public partial struct Next
     {
-        public Node? Node;
         public string? String;
+        public TopLevel? TopLevel;
 
-        public static implicit operator Next(Node Node) => new Next { Node = Node };
         public static implicit operator Next(string String) => new Next { String = String };
-        public bool IsNull => Node == null && String == null;
+        public static implicit operator Next(TopLevel TopLevel) => new Next { TopLevel = TopLevel };
+        public bool IsNull => TopLevel == null && String == null;
     }
 
     public partial class TopLevel
@@ -90,8 +81,8 @@ namespace QuickType
                     var stringValue = serializer.Deserialize<string>(reader);
                     return new Next { String = stringValue };
                 case JsonToken.StartObject:
-                    var objectValue = serializer.Deserialize<Node>(reader);
-                    return new Next { Node = objectValue };
+                    var objectValue = serializer.Deserialize<TopLevel>(reader);
+                    return new Next { TopLevel = objectValue };
             }
             throw new Exception("Cannot unmarshal type Next");
         }
@@ -109,9 +100,9 @@ namespace QuickType
                 serializer.Serialize(writer, value.String);
                 return;
             }
-            if (value.Node != null)
+            if (value.TopLevel != null)
             {
-                serializer.Serialize(writer, value.Node);
+                serializer.Serialize(writer, value.TopLevel);
                 return;
             }
             throw new Exception("Cannot marshal type Next");
diff --git a/head/schema-csharp-SystemTextJson/test/inputs/schema/recursive-ref-to-id.schema/default/QuickType.cs b/head/schema-csharp-SystemTextJson/test/inputs/schema/recursive-ref-to-id.schema/default/QuickType.cs
new file mode 100644
index 0000000..70a224a
--- /dev/null
+++ b/head/schema-csharp-SystemTextJson/test/inputs/schema/recursive-ref-to-id.schema/default/QuickType.cs
@@ -0,0 +1,177 @@
+// <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("children")]
+        public TopLevel[]? Children { get; set; }
+
+        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+        [JsonPropertyName("data")]
+        public Data? Data { get; set; }
+    }
+
+    public partial class Data
+    {
+        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+        [JsonPropertyName("id")]
+        public string? Id { get; set; }
+    }
+
+    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 =
+            {
+                new DateOnlyConverter(),
+                new TimeOnlyConverter(),
+                IsoDateTimeOffsetConverter.Singleton
+            },
+        };
+    }
+    
+    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/base/schema-csharp-SystemTextJson/test/inputs/schema/recursive-union-flattening.schema/default/QuickType.cs b/head/schema-csharp-SystemTextJson/test/inputs/schema/recursive-union-flattening.schema/default/QuickType.cs
index 2bd97e8..675f874 100644
--- a/base/schema-csharp-SystemTextJson/test/inputs/schema/recursive-union-flattening.schema/default/QuickType.cs
+++ b/head/schema-csharp-SystemTextJson/test/inputs/schema/recursive-union-flattening.schema/default/QuickType.cs
@@ -20,70 +20,46 @@ namespace QuickType
     using System.Text.Json.Serialization;
     using System.Globalization;
 
-    public partial class TopLevelClass
+    public partial class A
     {
         [JsonPropertyName("x")]
-        public X? X { get; set; }
+        public PurpleTopLevel? X { get; set; }
     }
 
-    public partial class XClass
-    {
-        [JsonPropertyName("x")]
-        public X? X { get; set; }
-    }
-
-    public partial struct X
-    {
-        public XElement[]? AnythingArray;
-        public Dictionary<string, object>? AnythingMap;
-        public bool? Bool;
-        public double? Double;
-        public long? Integer;
-        public string? String;
-
-        public static implicit operator X(XElement[] AnythingArray) => new X { AnythingArray = AnythingArray };
-        public static implicit operator X(Dictionary<string, object> AnythingMap) => new X { AnythingMap = AnythingMap };
-        public static implicit operator X(bool Bool) => new X { Bool = Bool };
-        public static implicit operator X(double Double) => new X { Double = Double };
-        public static implicit operator X(long Integer) => new X { Integer = Integer };
-        public static implicit operator X(string String) => new X { String = String };
-        public bool IsNull => AnythingArray == null && Bool == null && Double == null && Integer == null && AnythingMap == null && String == null;
-    }
-
-    public partial struct XElement
+    public partial struct TopLevelElement
     {
+        public A? A;
         public object[]? AnythingArray;
         public bool? Bool;
         public double? Double;
         public long? Integer;
         public string? String;
-        public XClass? XClass;
-
-        public static implicit operator XElement(object[] AnythingArray) => new XElement { AnythingArray = AnythingArray };
-        public static implicit operator XElement(bool Bool) => new XElement { Bool = Bool };
-        public static implicit operator XElement(double Double) => new XElement { Double = Double };
-        public static implicit operator XElement(long Integer) => new XElement { Integer = Integer };
-        public static implicit operator XElement(string String) => new XElement { String = String };
-        public static implicit operator XElement(XClass XClass) => new XElement { XClass = XClass };
-        public bool IsNull => AnythingArray == null && Bool == null && XClass == null && Double == null && Integer == null && String == null;
+
+        public static implicit operator TopLevelElement(A A) => new TopLevelElement { A = A };
+        public static implicit operator TopLevelElement(object[] AnythingArray) => new TopLevelElement { AnythingArray = AnythingArray };
+        public static implicit operator TopLevelElement(bool Bool) => new TopLevelElement { Bool = Bool };
+        public static implicit operator TopLevelElement(double Double) => new TopLevelElement { Double = Double };
+        public static implicit operator TopLevelElement(long Integer) => new TopLevelElement { Integer = Integer };
+        public static implicit operator TopLevelElement(string String) => new TopLevelElement { String = String };
+        public bool IsNull => AnythingArray == null && Bool == null && A == null && Double == null && Integer == null && String == null;
     }
 
-    public partial struct TopLevelElement
+    public partial struct PurpleTopLevel
     {
-        public object[]? AnythingArray;
+        public TopLevelElement[]? AnythingArray;
+        public Dictionary<string, object>? AnythingMap;
         public bool? Bool;
         public double? Double;
         public long? Integer;
         public string? String;
-        public TopLevelClass? TopLevelClass;
 
-        public static implicit operator TopLevelElement(object[] AnythingArray) => new TopLevelElement { AnythingArray = AnythingArray };
-        public static implicit operator TopLevelElement(bool Bool) => new TopLevelElement { Bool = Bool };
-        public static implicit operator TopLevelElement(double Double) => new TopLevelElement { Double = Double };
-        public static implicit operator TopLevelElement(long Integer) => new TopLevelElement { Integer = Integer };
-        public static implicit operator TopLevelElement(string String) => new TopLevelElement { String = String };
-        public static implicit operator TopLevelElement(TopLevelClass TopLevelClass) => new TopLevelElement { TopLevelClass = TopLevelClass };
-        public bool IsNull => AnythingArray == null && Bool == null && TopLevelClass == null && Double == null && Integer == null && String == null;
+        public static implicit operator PurpleTopLevel(TopLevelElement[] AnythingArray) => new PurpleTopLevel { AnythingArray = AnythingArray };
+        public static implicit operator PurpleTopLevel(Dictionary<string, object> AnythingMap) => new PurpleTopLevel { AnythingMap = AnythingMap };
+        public static implicit operator PurpleTopLevel(bool Bool) => new PurpleTopLevel { Bool = Bool };
+        public static implicit operator PurpleTopLevel(double Double) => new PurpleTopLevel { Double = Double };
+        public static implicit operator PurpleTopLevel(long Integer) => new PurpleTopLevel { Integer = Integer };
+        public static implicit operator PurpleTopLevel(string String) => new PurpleTopLevel { String = String };
+        public bool IsNull => AnythingArray == null && Bool == null && Double == null && Integer == null && AnythingMap == null && String == null;
     }
 
     public partial struct TopLevelUnion
@@ -122,8 +98,7 @@ namespace QuickType
             {
                 TopLevelUnionConverter.Singleton,
                 TopLevelElementConverter.Singleton,
-                XConverter.Singleton,
-                XElementConverter.Singleton,
+                PurpleTopLevelConverter.Singleton,
                 new DateOnlyConverter(),
                 new TimeOnlyConverter(),
                 IsoDateTimeOffsetConverter.Singleton
@@ -241,8 +216,8 @@ namespace QuickType
                     var stringValue = reader.GetString();
                     return new TopLevelElement { String = stringValue };
                 case JsonTokenType.StartObject:
-                    var objectValue = JsonSerializer.Deserialize<TopLevelClass>(ref reader, options);
-                    return new TopLevelElement { TopLevelClass = objectValue };
+                    var objectValue = JsonSerializer.Deserialize<A>(ref reader, options);
+                    return new TopLevelElement { A = objectValue };
                 case JsonTokenType.StartArray:
                     var arrayValue = JsonSerializer.Deserialize<object[]>(ref reader, options);
                     return new TopLevelElement { AnythingArray = arrayValue };
@@ -282,9 +257,9 @@ namespace QuickType
                 JsonSerializer.Serialize(writer, value.AnythingArray, options);
                 return;
             }
-            if (value.TopLevelClass != null)
+            if (value.A != null)
             {
-                JsonSerializer.Serialize(writer, value.TopLevelClass, options);
+                JsonSerializer.Serialize(writer, value.A, options);
                 return;
             }
             throw new NotSupportedException("Cannot marshal type TopLevelElement");
@@ -293,45 +268,45 @@ namespace QuickType
         public static readonly TopLevelElementConverter Singleton = new TopLevelElementConverter();
     }
 
-    internal class XConverter : JsonConverter<X>
+    internal class PurpleTopLevelConverter : JsonConverter<PurpleTopLevel>
     {
-        public override bool CanConvert(Type t) => t == typeof(X);
+        public override bool CanConvert(Type t) => t == typeof(PurpleTopLevel);
 
-        public override X Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+        public override PurpleTopLevel Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
         {
             switch (reader.TokenType)
             {
                 case JsonTokenType.Null:
-                    return new X { };
+                    return new PurpleTopLevel { };
                 case JsonTokenType.Number:
                     if (reader.TryGetInt64(out long intTryValue1))
                     {
                         var intValue2 = reader.GetInt64();
-                        return new X { Integer = intValue2 };
+                        return new PurpleTopLevel { Integer = intValue2 };
                     }
                     else
                     {
                         var doubleValue3 = reader.GetDouble();
-                        return new X { Double = doubleValue3 };
+                        return new PurpleTopLevel { Double = doubleValue3 };
                     }
                 case JsonTokenType.True:
                 case JsonTokenType.False:
                     var boolValue = reader.GetBoolean();
-                    return new X { Bool = boolValue };
+                    return new PurpleTopLevel { Bool = boolValue };
                 case JsonTokenType.String:
                     var stringValue = reader.GetString();
-                    return new X { String = stringValue };
+                    return new PurpleTopLevel { String = stringValue };
                 case JsonTokenType.StartObject:
                     var objectValue = JsonSerializer.Deserialize<Dictionary<string, object>>(ref reader, options);
-                    return new X { AnythingMap = objectValue };
+                    return new PurpleTopLevel { AnythingMap = objectValue };
                 case JsonTokenType.StartArray:
-                    var arrayValue = JsonSerializer.Deserialize<XElement[]>(ref reader, options);
-                    return new X { AnythingArray = arrayValue };
+                    var arrayValue = JsonSerializer.Deserialize<TopLevelElement[]>(ref reader, options);
+                    return new PurpleTopLevel { AnythingArray = arrayValue };
             }
-            throw new JsonException("Cannot unmarshal type X");
+            throw new JsonException("Cannot unmarshal type PurpleTopLevel");
         }
 
-        public override void Write(Utf8JsonWriter writer, X value, JsonSerializerOptions options)
+        public override void Write(Utf8JsonWriter writer, PurpleTopLevel value, JsonSerializerOptions options)
         {
             if (value.IsNull)
             {
@@ -368,91 +343,10 @@ namespace QuickType
                 JsonSerializer.Serialize(writer, value.AnythingMap, options);
                 return;
             }
-            throw new NotSupportedException("Cannot marshal type X");
-        }
-
-        public static readonly XConverter Singleton = new XConverter();
-    }
-
-    internal class XElementConverter : JsonConverter<XElement>
-    {
-        public override bool CanConvert(Type t) => t == typeof(XElement);
-
-        public override XElement Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
-        {
-            switch (reader.TokenType)
-            {
-                case JsonTokenType.Null:
-                    return new XElement { };
-                case JsonTokenType.Number:
-                    if (reader.TryGetInt64(out long intTryValue1))
-                    {
-                        var intValue2 = reader.GetInt64();
-                        return new XElement { Integer = intValue2 };
-                    }
-                    else
-                    {
-                        var doubleValue3 = reader.GetDouble();
-                        return new XElement { Double = doubleValue3 };
-                    }
-                case JsonTokenType.True:
-                case JsonTokenType.False:
-                    var boolValue = reader.GetBoolean();
-                    return new XElement { Bool = boolValue };
-                case JsonTokenType.String:
-                    var stringValue = reader.GetString();
-                    return new XElement { String = stringValue };
-                case JsonTokenType.StartObject:
-                    var objectValue = JsonSerializer.Deserialize<XClass>(ref reader, options);
-                    return new XElement { XClass = objectValue };
-                case JsonTokenType.StartArray:
-                    var arrayValue = JsonSerializer.Deserialize<object[]>(ref reader, options);
-                    return new XElement { AnythingArray = arrayValue };
-            }
-            throw new JsonException("Cannot unmarshal type XElement");
-        }
-
-        public override void Write(Utf8JsonWriter writer, XElement value, JsonSerializerOptions options)
-        {
-            if (value.IsNull)
-            {
-                writer.WriteNullValue();
-                return;
-            }
-            if (value.Integer != null)
-            {
-                JsonSerializer.Serialize(writer, value.Integer.Value, options);
-                return;
-            }
-            if (value.Double != null)
-            {
-                JsonSerializer.Serialize(writer, value.Double.Value, options);
-                return;
-            }
-            if (value.Bool != null)
-            {
-                JsonSerializer.Serialize(writer, value.Bool.Value, options);
-                return;
-            }
-            if (value.String != null)
-            {
-                JsonSerializer.Serialize(writer, value.String, options);
-                return;
-            }
-            if (value.AnythingArray != null)
-            {
-                JsonSerializer.Serialize(writer, value.AnythingArray, options);
-                return;
-            }
-            if (value.XClass != null)
-            {
-                JsonSerializer.Serialize(writer, value.XClass, options);
-                return;
-            }
-            throw new NotSupportedException("Cannot marshal type XElement");
+            throw new NotSupportedException("Cannot marshal type PurpleTopLevel");
         }
 
-        public static readonly XElementConverter Singleton = new XElementConverter();
+        public static readonly PurpleTopLevelConverter Singleton = new PurpleTopLevelConverter();
     }
     
     public class DateOnlyConverter : JsonConverter<DateOnly>
diff --git a/base/schema-csharp-SystemTextJson/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.cs b/head/schema-csharp-SystemTextJson/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.cs
index 1aaef3f..3a745e4 100644
--- a/base/schema-csharp-SystemTextJson/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.cs
+++ b/head/schema-csharp-SystemTextJson/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.cs
@@ -30,24 +30,14 @@ namespace QuickType
         public string Value { get; set; }
     }
 
-    public partial class Node
-    {
-        [JsonPropertyName("next")]
-        public Next? Next { get; set; }
-
-        [JsonRequired]
-        [JsonPropertyName("value")]
-        public string Value { get; set; }
-    }
-
     public partial struct Next
     {
-        public Node? Node;
         public string? String;
+        public TopLevel? TopLevel;
 
-        public static implicit operator Next(Node Node) => new Next { Node = Node };
         public static implicit operator Next(string String) => new Next { String = String };
-        public bool IsNull => Node == null && String == null;
+        public static implicit operator Next(TopLevel TopLevel) => new Next { TopLevel = TopLevel };
+        public bool IsNull => TopLevel == null && String == null;
     }
 
     public partial class TopLevel
@@ -88,8 +78,8 @@ namespace QuickType
                     var stringValue = reader.GetString();
                     return new Next { String = stringValue };
                 case JsonTokenType.StartObject:
-                    var objectValue = JsonSerializer.Deserialize<Node>(ref reader, options);
-                    return new Next { Node = objectValue };
+                    var objectValue = JsonSerializer.Deserialize<TopLevel>(ref reader, options);
+                    return new Next { TopLevel = objectValue };
             }
             throw new JsonException("Cannot unmarshal type Next");
         }
@@ -106,9 +96,9 @@ namespace QuickType
                 JsonSerializer.Serialize(writer, value.String, options);
                 return;
             }
-            if (value.Node != null)
+            if (value.TopLevel != null)
             {
-                JsonSerializer.Serialize(writer, value.Node, options);
+                JsonSerializer.Serialize(writer, value.TopLevel, options);
                 return;
             }
             throw new NotSupportedException("Cannot marshal type Next");
diff --git a/head/schema-csharp-records/test/inputs/schema/recursive-ref-to-id.schema/default/QuickType.cs b/head/schema-csharp-records/test/inputs/schema/recursive-ref-to-id.schema/default/QuickType.cs
new file mode 100644
index 0000000..3e37ee7
--- /dev/null
+++ b/head/schema-csharp-records/test/inputs/schema/recursive-ref-to-id.schema/default/QuickType.cs
@@ -0,0 +1,70 @@
+// <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("children", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public TopLevel[]? Children { get; set; }
+
+        [JsonProperty("data", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public Data? Data { get; set; }
+    }
+
+    public partial record Data
+    {
+        [JsonProperty("id", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public string? Id { get; set; }
+    }
+
+    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 =
+            {
+                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
+            },
+        };
+    }
+}
+#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/base/schema-csharp-records/test/inputs/schema/recursive-union-flattening.schema/default/QuickType.cs b/head/schema-csharp-records/test/inputs/schema/recursive-union-flattening.schema/default/QuickType.cs
index 0283afa..bec82de 100644
--- a/base/schema-csharp-records/test/inputs/schema/recursive-union-flattening.schema/default/QuickType.cs
+++ b/head/schema-csharp-records/test/inputs/schema/recursive-union-flattening.schema/default/QuickType.cs
@@ -23,70 +23,46 @@ namespace QuickType
     using Newtonsoft.Json;
     using Newtonsoft.Json.Converters;
 
-    public partial record TopLevelClass
+    public partial record A
     {
         [JsonProperty("x")]
-        public X? X { get; set; }
+        public PurpleTopLevel? X { get; set; }
     }
 
-    public partial record XClass
-    {
-        [JsonProperty("x")]
-        public X? X { get; set; }
-    }
-
-    public partial struct X
-    {
-        public XElement[]? AnythingArray;
-        public Dictionary<string, object>? AnythingMap;
-        public bool? Bool;
-        public double? Double;
-        public long? Integer;
-        public string? String;
-
-        public static implicit operator X(XElement[] AnythingArray) => new X { AnythingArray = AnythingArray };
-        public static implicit operator X(Dictionary<string, object> AnythingMap) => new X { AnythingMap = AnythingMap };
-        public static implicit operator X(bool Bool) => new X { Bool = Bool };
-        public static implicit operator X(double Double) => new X { Double = Double };
-        public static implicit operator X(long Integer) => new X { Integer = Integer };
-        public static implicit operator X(string String) => new X { String = String };
-        public bool IsNull => AnythingArray == null && Bool == null && Double == null && Integer == null && AnythingMap == null && String == null;
-    }
-
-    public partial struct XElement
+    public partial struct TopLevelElement
     {
+        public A? A;
         public object[]? AnythingArray;
         public bool? Bool;
         public double? Double;
         public long? Integer;
         public string? String;
-        public XClass? XClass;
 
-        public static implicit operator XElement(object[] AnythingArray) => new XElement { AnythingArray = AnythingArray };
-        public static implicit operator XElement(bool Bool) => new XElement { Bool = Bool };
-        public static implicit operator XElement(double Double) => new XElement { Double = Double };
-        public static implicit operator XElement(long Integer) => new XElement { Integer = Integer };
-        public static implicit operator XElement(string String) => new XElement { String = String };
-        public static implicit operator XElement(XClass XClass) => new XElement { XClass = XClass };
-        public bool IsNull => AnythingArray == null && Bool == null && XClass == null && Double == null && Integer == null && String == null;
+        public static implicit operator TopLevelElement(A A) => new TopLevelElement { A = A };
+        public static implicit operator TopLevelElement(object[] AnythingArray) => new TopLevelElement { AnythingArray = AnythingArray };
+        public static implicit operator TopLevelElement(bool Bool) => new TopLevelElement { Bool = Bool };
+        public static implicit operator TopLevelElement(double Double) => new TopLevelElement { Double = Double };
+        public static implicit operator TopLevelElement(long Integer) => new TopLevelElement { Integer = Integer };
+        public static implicit operator TopLevelElement(string String) => new TopLevelElement { String = String };
+        public bool IsNull => AnythingArray == null && Bool == null && A == null && Double == null && Integer == null && String == null;
     }
 
-    public partial struct TopLevelElement
+    public partial struct PurpleTopLevel
     {
-        public object[]? AnythingArray;
+        public TopLevelElement[]? AnythingArray;
+        public Dictionary<string, object>? AnythingMap;
         public bool? Bool;
         public double? Double;
         public long? Integer;
         public string? String;
-        public TopLevelClass? TopLevelClass;
 
-        public static implicit operator TopLevelElement(object[] AnythingArray) => new TopLevelElement { AnythingArray = AnythingArray };
-        public static implicit operator TopLevelElement(bool Bool) => new TopLevelElement { Bool = Bool };
-        public static implicit operator TopLevelElement(double Double) => new TopLevelElement { Double = Double };
-        public static implicit operator TopLevelElement(long Integer) => new TopLevelElement { Integer = Integer };
-        public static implicit operator TopLevelElement(string String) => new TopLevelElement { String = String };
-        public static implicit operator TopLevelElement(TopLevelClass TopLevelClass) => new TopLevelElement { TopLevelClass = TopLevelClass };
-        public bool IsNull => AnythingArray == null && Bool == null && TopLevelClass == null && Double == null && Integer == null && String == null;
+        public static implicit operator PurpleTopLevel(TopLevelElement[] AnythingArray) => new PurpleTopLevel { AnythingArray = AnythingArray };
+        public static implicit operator PurpleTopLevel(Dictionary<string, object> AnythingMap) => new PurpleTopLevel { AnythingMap = AnythingMap };
+        public static implicit operator PurpleTopLevel(bool Bool) => new PurpleTopLevel { Bool = Bool };
+        public static implicit operator PurpleTopLevel(double Double) => new PurpleTopLevel { Double = Double };
+        public static implicit operator PurpleTopLevel(long Integer) => new PurpleTopLevel { Integer = Integer };
+        public static implicit operator PurpleTopLevel(string String) => new PurpleTopLevel { String = String };
+        public bool IsNull => AnythingArray == null && Bool == null && Double == null && Integer == null && AnythingMap == null && String == null;
     }
 
     public partial struct TopLevelUnion
@@ -127,8 +103,7 @@ namespace QuickType
             {
                 TopLevelUnionConverter.Singleton,
                 TopLevelElementConverter.Singleton,
-                XConverter.Singleton,
-                XElementConverter.Singleton,
+                PurpleTopLevelConverter.Singleton,
                 new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
             },
         };
@@ -235,8 +210,8 @@ namespace QuickType
                     var stringValue = serializer.Deserialize<string>(reader);
                     return new TopLevelElement { String = stringValue };
                 case JsonToken.StartObject:
-                    var objectValue = serializer.Deserialize<TopLevelClass>(reader);
-                    return new TopLevelElement { TopLevelClass = objectValue };
+                    var objectValue = serializer.Deserialize<A>(reader);
+                    return new TopLevelElement { A = objectValue };
                 case JsonToken.StartArray:
                     var arrayValue = serializer.Deserialize<object[]>(reader);
                     return new TopLevelElement { AnythingArray = arrayValue };
@@ -277,9 +252,9 @@ namespace QuickType
                 serializer.Serialize(writer, value.AnythingArray);
                 return;
             }
-            if (value.TopLevelClass != null)
+            if (value.A != null)
             {
-                serializer.Serialize(writer, value.TopLevelClass);
+                serializer.Serialize(writer, value.A);
                 return;
             }
             throw new Exception("Cannot marshal type TopLevelElement");
@@ -288,42 +263,42 @@ namespace QuickType
         public static readonly TopLevelElementConverter Singleton = new TopLevelElementConverter();
     }
 
-    internal class XConverter : JsonConverter
+    internal class PurpleTopLevelConverter : JsonConverter
     {
-        public override bool CanConvert(Type t) => t == typeof(X) || t == typeof(X?);
+        public override bool CanConvert(Type t) => t == typeof(PurpleTopLevel) || t == typeof(PurpleTopLevel?);
 
         public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
         {
             switch (reader.TokenType)
             {
                 case JsonToken.Null:
-                    return new X { };
+                    return new PurpleTopLevel { };
                 case JsonToken.Integer:
                     var integerValue = serializer.Deserialize<long>(reader);
-                    return new X { Integer = integerValue };
+                    return new PurpleTopLevel { Integer = integerValue };
                 case JsonToken.Float:
                     var doubleValue = serializer.Deserialize<double>(reader);
-                    return new X { Double = doubleValue };
+                    return new PurpleTopLevel { Double = doubleValue };
                 case JsonToken.Boolean:
                     var boolValue = serializer.Deserialize<bool>(reader);
-                    return new X { Bool = boolValue };
+                    return new PurpleTopLevel { Bool = boolValue };
                 case JsonToken.String:
                 case JsonToken.Date:
                     var stringValue = serializer.Deserialize<string>(reader);
-                    return new X { String = stringValue };
+                    return new PurpleTopLevel { String = stringValue };
                 case JsonToken.StartObject:
                     var objectValue = serializer.Deserialize<Dictionary<string, object>>(reader);
-                    return new X { AnythingMap = objectValue };
+                    return new PurpleTopLevel { AnythingMap = objectValue };
                 case JsonToken.StartArray:
-                    var arrayValue = serializer.Deserialize<XElement[]>(reader);
-                    return new X { AnythingArray = arrayValue };
+                    var arrayValue = serializer.Deserialize<TopLevelElement[]>(reader);
+                    return new PurpleTopLevel { AnythingArray = arrayValue };
             }
-            throw new Exception("Cannot unmarshal type X");
+            throw new Exception("Cannot unmarshal type PurpleTopLevel");
         }
 
         public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
         {
-            var value = (X)untypedValue;
+            var value = (PurpleTopLevel)untypedValue;
             if (value.IsNull)
             {
                 serializer.Serialize(writer, null);
@@ -359,87 +334,10 @@ namespace QuickType
                 serializer.Serialize(writer, value.AnythingMap);
                 return;
             }
-            throw new Exception("Cannot marshal type X");
-        }
-
-        public static readonly XConverter Singleton = new XConverter();
-    }
-
-    internal class XElementConverter : JsonConverter
-    {
-        public override bool CanConvert(Type t) => t == typeof(XElement) || t == typeof(XElement?);
-
-        public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
-        {
-            switch (reader.TokenType)
-            {
-                case JsonToken.Null:
-                    return new XElement { };
-                case JsonToken.Integer:
-                    var integerValue = serializer.Deserialize<long>(reader);
-                    return new XElement { Integer = integerValue };
-                case JsonToken.Float:
-                    var doubleValue = serializer.Deserialize<double>(reader);
-                    return new XElement { Double = doubleValue };
-                case JsonToken.Boolean:
-                    var boolValue = serializer.Deserialize<bool>(reader);
-                    return new XElement { Bool = boolValue };
-                case JsonToken.String:
-                case JsonToken.Date:
-                    var stringValue = serializer.Deserialize<string>(reader);
-                    return new XElement { String = stringValue };
-                case JsonToken.StartObject:
-                    var objectValue = serializer.Deserialize<XClass>(reader);
-                    return new XElement { XClass = objectValue };
-                case JsonToken.StartArray:
-                    var arrayValue = serializer.Deserialize<object[]>(reader);
-                    return new XElement { AnythingArray = arrayValue };
-            }
-            throw new Exception("Cannot unmarshal type XElement");
-        }
-
-        public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
-        {
-            var value = (XElement)untypedValue;
-            if (value.IsNull)
-            {
-                serializer.Serialize(writer, null);
-                return;
-            }
-            if (value.Integer != null)
-            {
-                serializer.Serialize(writer, value.Integer.Value);
-                return;
-            }
-            if (value.Double != null)
-            {
-                serializer.Serialize(writer, value.Double.Value);
-                return;
-            }
-            if (value.Bool != null)
-            {
-                serializer.Serialize(writer, value.Bool.Value);
-                return;
-            }
-            if (value.String != null)
-            {
-                serializer.Serialize(writer, value.String);
-                return;
-            }
-            if (value.AnythingArray != null)
-            {
-                serializer.Serialize(writer, value.AnythingArray);
-                return;
-            }
-            if (value.XClass != null)
-            {
-                serializer.Serialize(writer, value.XClass);
-                return;
-            }
-            throw new Exception("Cannot marshal type XElement");
+            throw new Exception("Cannot marshal type PurpleTopLevel");
         }
 
-        public static readonly XElementConverter Singleton = new XElementConverter();
+        public static readonly PurpleTopLevelConverter Singleton = new PurpleTopLevelConverter();
     }
 }
 #pragma warning restore CS8618
diff --git a/base/schema-csharp-records/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.cs b/head/schema-csharp-records/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.cs
index ad8e5a0..f27a683 100644
--- a/base/schema-csharp-records/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.cs
+++ b/head/schema-csharp-records/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.cs
@@ -32,23 +32,14 @@ namespace QuickType
         public string Value { get; set; }
     }
 
-    public partial record Node
-    {
-        [JsonProperty("next")]
-        public Next? Next { get; set; }
-
-        [JsonProperty("value", Required = Required.Always)]
-        public string Value { get; set; }
-    }
-
     public partial struct Next
     {
-        public Node? Node;
         public string? String;
+        public TopLevel? TopLevel;
 
-        public static implicit operator Next(Node Node) => new Next { Node = Node };
         public static implicit operator Next(string String) => new Next { String = String };
-        public bool IsNull => Node == null && String == null;
+        public static implicit operator Next(TopLevel TopLevel) => new Next { TopLevel = TopLevel };
+        public bool IsNull => TopLevel == null && String == null;
     }
 
     public partial record TopLevel
@@ -90,8 +81,8 @@ namespace QuickType
                     var stringValue = serializer.Deserialize<string>(reader);
                     return new Next { String = stringValue };
                 case JsonToken.StartObject:
-                    var objectValue = serializer.Deserialize<Node>(reader);
-                    return new Next { Node = objectValue };
+                    var objectValue = serializer.Deserialize<TopLevel>(reader);
+                    return new Next { TopLevel = objectValue };
             }
             throw new Exception("Cannot unmarshal type Next");
         }
@@ -109,9 +100,9 @@ namespace QuickType
                 serializer.Serialize(writer, value.String);
                 return;
             }
-            if (value.Node != null)
+            if (value.TopLevel != null)
             {
-                serializer.Serialize(writer, value.Node);
+                serializer.Serialize(writer, value.TopLevel);
                 return;
             }
             throw new Exception("Cannot marshal type Next");
diff --git a/base/schema-dart/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.dart b/head/schema-dart/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.dart
index 907cf83..ed8e11a 100644
--- a/base/schema-dart/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.dart
+++ b/head/schema-dart/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.dart
@@ -8,30 +8,14 @@ dynamic topLevelFromJson(String str) => json.decode(str);
 
 String topLevelToJson(dynamic data) => json.encode(data);
 
-class TopLevelClass {
+class A {
     final dynamic x;
 
-    TopLevelClass({
+    A({
         this.x,
     });
 
-    factory TopLevelClass.fromJson(Map<String, dynamic> json) => TopLevelClass(
-        x: json["x"],
-    );
-
-    Map<String, dynamic> toJson() => {
-        "x": x,
-    };
-}
-
-class XClass {
-    final dynamic x;
-
-    XClass({
-        this.x,
-    });
-
-    factory XClass.fromJson(Map<String, dynamic> json) => XClass(
+    factory A.fromJson(Map<String, dynamic> json) => A(
         x: json["x"],
     );
 
diff --git a/base/schema-dart/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.dart b/head/schema-dart/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.dart
index 6b0876b..787e622 100644
--- a/base/schema-dart/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.dart
+++ b/head/schema-dart/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.dart
@@ -27,23 +27,3 @@ class TopLevel {
         "value": value,
     };
 }
-
-class Node {
-    final dynamic next;
-    final String value;
-
-    Node({
-        this.next,
-        required this.value,
-    });
-
-    factory Node.fromJson(Map<String, dynamic> json) => Node(
-        next: json["next"],
-        value: json["value"],
-    );
-
-    Map<String, dynamic> toJson() => {
-        "next": next,
-        "value": value,
-    };
-}
diff --git a/head/schema-elixir/test/inputs/schema/recursive-ref-to-id.schema/default/QuickType.ex b/head/schema-elixir/test/inputs/schema/recursive-ref-to-id.schema/default/QuickType.ex
new file mode 100644
index 0000000..dada0b8
--- /dev/null
+++ b/head/schema-elixir/test/inputs/schema/recursive-ref-to-id.schema/default/QuickType.ex
@@ -0,0 +1,73 @@
+# 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 Data do
+  defstruct [:id]
+
+  @type t :: %__MODULE__{
+          id: String.t() | nil
+        }
+
+  def from_map(m) do
+    %Data{
+      id: m["id"],
+    }
+  end
+
+  def from_json(json) do
+    json
+          |> Jason.decode!()
+          |> from_map()
+  end
+
+  def to_map(struct) do
+    %{
+      "id" => struct.id,
+    }
+  end
+
+  def to_json(struct) do
+    struct
+          |> to_map()
+          |> Jason.encode!()
+  end
+end
+
+defmodule TopLevel do
+  defstruct [:children, :data]
+
+  @type t :: %__MODULE__{
+          children: [TopLevel.t()] | nil,
+          data: Data.t() | nil
+        }
+
+  def from_map(m) do
+    %TopLevel{
+      children: m["children"] && Enum.map(m["children"], &TopLevel.from_map/1),
+      data: m["data"] && Data.from_map(m["data"]),
+    }
+  end
+
+  def from_json(json) do
+    json
+          |> Jason.decode!()
+          |> from_map()
+  end
+
+  def to_map(struct) do
+    %{
+      "children" => struct.children && Enum.map(struct.children, &TopLevel.to_map/1),
+      "data" => struct.data && Data.to_map(struct.data),
+    }
+  end
+
+  def to_json(struct) do
+    struct
+          |> to_map()
+          |> Jason.encode!()
+  end
+end
diff --git a/base/schema-elixir/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.ex b/head/schema-elixir/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.ex
index 43f4cff..3f845a2 100644
--- a/base/schema-elixir/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.ex
+++ b/head/schema-elixir/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.ex
@@ -5,67 +5,21 @@
 # Decode a JSON string: TopLevel.from_json(data)
 # Encode into a JSON string: TopLevel.to_json(struct)
 
-defmodule NodeClass do
-  @enforce_keys [:value]
-  defstruct [:next, :value]
-
-  @type t :: %__MODULE__{
-          next: NodeClass.t() | nil | String.t() | nil,
-          value: String.t()
-        }
-
-  def decode_next(%{"value" => _,} = value), do: NodeClass.from_map(value)
-  def decode_next(value) when is_nil(value), do: value
-  def decode_next(value) when is_binary(value), do: value
-  def decode_next(_), do: {:error, "Unexpected type when decoding NodeClass.next"}
-
-  def encode_next(%NodeClass{} = value), do: NodeClass.to_map(value)
-  def encode_next(value) when is_nil(value), do: value
-  def encode_next(value) when is_binary(value), do: value
-  def encode_next(_), do: {:error, "Unexpected type when encoding NodeClass.next"}
-
-  def from_map(m) do
-    %NodeClass{
-      next: decode_next(m["next"]),
-      value: m["value"],
-    }
-  end
-
-  def from_json(json) do
-    json
-          |> Jason.decode!()
-          |> from_map()
-  end
-
-  def to_map(struct) do
-    %{
-      "next" => encode_next(struct.next),
-      "value" => struct.value,
-    }
-  end
-
-  def to_json(struct) do
-    struct
-          |> to_map()
-          |> Jason.encode!()
-  end
-end
-
 defmodule TopLevel do
   @enforce_keys [:value]
   defstruct [:next, :value]
 
   @type t :: %__MODULE__{
-          next: NodeClass.t() | nil | String.t() | nil,
+          next: TopLevel.t() | nil | String.t() | nil,
           value: String.t()
         }
 
-  def decode_next(%{"value" => _,} = value), do: NodeClass.from_map(value)
+  def decode_next(%{"value" => _,} = value), do: TopLevel.from_map(value)
   def decode_next(value) when is_nil(value), do: value
   def decode_next(value) when is_binary(value), do: value
   def decode_next(_), do: {:error, "Unexpected type when decoding TopLevel.next"}
 
-  def encode_next(%NodeClass{} = value), do: NodeClass.to_map(value)
+  def encode_next(%TopLevel{} = value), do: TopLevel.to_map(value)
   def encode_next(value) when is_nil(value), do: value
   def encode_next(value) when is_binary(value), do: value
   def encode_next(_), do: {:error, "Unexpected type when encoding TopLevel.next"}
diff --git a/head/schema-flow/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.js b/head/schema-flow/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.js
new file mode 100644
index 0000000..5f3aaef
--- /dev/null
+++ b/head/schema-flow/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.js
@@ -0,0 +1,199 @@
+// @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 = {
+    children?: TopLevel[];
+    data?:     Data;
+    [property: string]: mixed;
+};
+
+export type Data = {
+    id?: string;
+    [property: string]: mixed;
+};
+
+// 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: "children", js: "children", typ: u(undefined, a(r("TopLevel"))) },
+        { json: "data", js: "data", typ: u(undefined, r("Data")) },
+    ], "any"),
+    "Data": o([
+        { json: "id", js: "id", typ: u(undefined, "") },
+    ], "any"),
+};
+
+module.exports = {
+    "topLevelToJson": topLevelToJson,
+    "toTopLevel": toTopLevel,
+};
diff --git a/base/schema-flow/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.js b/head/schema-flow/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.js
index fc5ba60..99295b3 100644
--- a/base/schema-flow/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.js
+++ b/head/schema-flow/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.js
@@ -11,30 +11,23 @@
 
 export type TopLevel = TopLevelElement[] | boolean | number | number | { [key: string]: mixed } | null | string;
 
-export type TopLevelElement = mixed[] | boolean | number | null | TopLevelObject | string;
+export type PurpleTopLevel = TopLevelElement[] | boolean | number | { [key: string]: mixed } | null | string;
 
-export type TopLevelObject = {
-    x?: X;
+export type A = {
+    x?: PurpleTopLevel;
     [property: string]: mixed;
 };
 
-export type XObject = {
-    x?: X;
-    [property: string]: mixed;
-};
-
-export type XElement = mixed[] | boolean | number | null | XObject | string;
-
-export type X = XElement[] | boolean | number | { [key: string]: mixed } | null | string;
+export type TopLevelElement = mixed[] | boolean | number | null | A | string;
 
 // 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), u(a(u(a("any"), true, 3.14, null, r("TopLevelObject"), "")), true, 3.14, 0, m("any"), null, ""));
+    return cast(JSON.parse(json), u(a(u(a("any"), true, 3.14, null, r("A"), "")), true, 3.14, 0, m("any"), null, ""));
 }
 
 function topLevelToJson(value: TopLevel): string {
-    return JSON.stringify(uncast(value, u(a(u(a("any"), true, 3.14, null, r("TopLevelObject"), "")), true, 3.14, 0, m("any"), null, "")), null, 2);
+    return JSON.stringify(uncast(value, u(a(u(a("any"), true, 3.14, null, r("A"), "")), true, 3.14, 0, m("any"), null, "")), null, 2);
 }
 
 function invalidValue(typ: any, val: any, key: any, parent: any = '') {
@@ -191,11 +184,8 @@ function r(name: string) {
 }
 
 const typeMap: any = {
-    "TopLevelObject": o([
-        { json: "x", js: "x", typ: u(undefined, u(a(u(a("any"), true, 3.14, null, r("XObject"), "")), true, 3.14, m("any"), null, "")) },
-    ], "any"),
-    "XObject": o([
-        { json: "x", js: "x", typ: u(undefined, u(a(u(a("any"), true, 3.14, null, r("XObject"), "")), true, 3.14, m("any"), null, "")) },
+    "A": o([
+        { json: "x", js: "x", typ: u(undefined, u(a(u(a("any"), true, 3.14, null, r("A"), "")), true, 3.14, m("any"), null, "")) },
     ], "any"),
 };
 
diff --git a/base/schema-flow/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.js b/head/schema-flow/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.js
index 87dc243..30bb539 100644
--- a/base/schema-flow/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.js
+++ b/head/schema-flow/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.js
@@ -9,20 +9,14 @@
 // These functions will throw an error if the JSON doesn't
 // match the expected interface, even if the JSON is valid.
 
-export type TopLevel = {
-    next?: Next;
-    value: string;
-    [property: string]: mixed;
-};
+export type Next = null | TopLevel | string;
 
-export type Node = {
+export type TopLevel = {
     next?: Next;
     value: string;
     [property: string]: mixed;
 };
 
-export type Next = null | Node | string;
-
 // Converts JSON strings to/from your types
 // and asserts the results of JSON.parse at runtime
 function toTopLevel(json: string): TopLevel {
@@ -188,11 +182,7 @@ function r(name: string) {
 
 const typeMap: any = {
     "TopLevel": o([
-        { json: "next", js: "next", typ: u(undefined, u(null, r("Node"), "")) },
-        { json: "value", js: "value", typ: "" },
-    ], "any"),
-    "Node": o([
-        { json: "next", js: "next", typ: u(undefined, u(null, r("Node"), "")) },
+        { json: "next", js: "next", typ: u(undefined, u(null, r("TopLevel"), "")) },
         { json: "value", js: "value", typ: "" },
     ], "any"),
 };
diff --git a/head/schema-golang/test/inputs/schema/recursive-ref-to-id.schema/default/quicktype.go b/head/schema-golang/test/inputs/schema/recursive-ref-to-id.schema/default/quicktype.go
new file mode 100644
index 0000000..32df350
--- /dev/null
+++ b/head/schema-golang/test/inputs/schema/recursive-ref-to-id.schema/default/quicktype.go
@@ -0,0 +1,28 @@
+// 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 "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 {
+	Children []TopLevel `json:"children,omitempty"`
+	Data     *Data      `json:"data,omitempty"`
+}
+
+type Data struct {
+	ID *string `json:"id,omitempty"`
+}
diff --git a/base/schema-golang/test/inputs/schema/recursive-union-flattening.schema/default/quicktype.go b/head/schema-golang/test/inputs/schema/recursive-union-flattening.schema/default/quicktype.go
index 200a80a..eb7ece3 100644
--- a/base/schema-golang/test/inputs/schema/recursive-union-flattening.schema/default/quicktype.go
+++ b/head/schema-golang/test/inputs/schema/recursive-union-flattening.schema/default/quicktype.go
@@ -21,12 +21,8 @@ func (r *TopLevel) Marshal() ([]byte, error) {
 	return json.Marshal(r)
 }
 
-type TopLevelClass struct {
-	X *X `json:"x"`
-}
-
-type XClass struct {
-	X *X `json:"x"`
+type A struct {
+	X *PurpleTopLevel `json:"x"`
 }
 
 type TopLevel struct {
@@ -54,83 +50,56 @@ func (x *TopLevel) MarshalJSON() ([]byte, error) {
 	return marshalUnion(x.Integer, x.Double, x.Bool, x.String, x.UnionArray != nil, x.UnionArray, false, nil, x.AnythingMap != nil, x.AnythingMap, false, nil, true)
 }
 
-type TopLevelElement struct {
-	AnythingArray []interface{}
-	Bool          *bool
-	Double        *float64
-	Integer       *int64
-	String        *string
-	TopLevelClass *TopLevelClass
+type PurpleTopLevel struct {
+	AnythingMap map[string]interface{}
+	Bool        *bool
+	Double      *float64
+	Integer     *int64
+	String      *string
+	UnionArray  []TopLevelElement
 }
 
-func (x *TopLevelElement) UnmarshalJSON(data []byte) error {
-	x.AnythingArray = nil
-	x.TopLevelClass = nil
-	var c TopLevelClass
-	object, err := unmarshalUnion(data, &x.Integer, &x.Double, &x.Bool, &x.String, true, &x.AnythingArray, true, &c, false, nil, false, nil, true)
+func (x *PurpleTopLevel) UnmarshalJSON(data []byte) error {
+	x.UnionArray = nil
+	x.AnythingMap = nil
+	object, err := unmarshalUnion(data, &x.Integer, &x.Double, &x.Bool, &x.String, true, &x.UnionArray, false, nil, true, &x.AnythingMap, false, nil, true)
 	if err != nil {
 		return err
 	}
 	if object {
-		x.TopLevelClass = &c
 	}
 	return nil
 }
 
-func (x *TopLevelElement) MarshalJSON() ([]byte, error) {
-	return marshalUnion(x.Integer, x.Double, x.Bool, x.String, x.AnythingArray != nil, x.AnythingArray, x.TopLevelClass != nil, x.TopLevelClass, false, nil, false, nil, true)
+func (x *PurpleTopLevel) MarshalJSON() ([]byte, error) {
+	return marshalUnion(x.Integer, x.Double, x.Bool, x.String, x.UnionArray != nil, x.UnionArray, false, nil, x.AnythingMap != nil, x.AnythingMap, false, nil, true)
 }
 
-type XElement struct {
+type TopLevelElement struct {
+	A             *A
 	AnythingArray []interface{}
 	Bool          *bool
 	Double        *float64
 	Integer       *int64
 	String        *string
-	XClass        *XClass
 }
 
-func (x *XElement) UnmarshalJSON(data []byte) error {
+func (x *TopLevelElement) UnmarshalJSON(data []byte) error {
 	x.AnythingArray = nil
-	x.XClass = nil
-	var c XClass
+	x.A = nil
+	var c A
 	object, err := unmarshalUnion(data, &x.Integer, &x.Double, &x.Bool, &x.String, true, &x.AnythingArray, true, &c, false, nil, false, nil, true)
 	if err != nil {
 		return err
 	}
 	if object {
-		x.XClass = &c
+		x.A = &c
 	}
 	return nil
 }
 
-func (x *XElement) MarshalJSON() ([]byte, error) {
-	return marshalUnion(x.Integer, x.Double, x.Bool, x.String, x.AnythingArray != nil, x.AnythingArray, x.XClass != nil, x.XClass, false, nil, false, nil, true)
-}
-
-type X struct {
-	AnythingMap map[string]interface{}
-	Bool        *bool
-	Double      *float64
-	Integer     *int64
-	String      *string
-	UnionArray  []XElement
-}
-
-func (x *X) UnmarshalJSON(data []byte) error {
-	x.UnionArray = nil
-	x.AnythingMap = nil
-	object, err := unmarshalUnion(data, &x.Integer, &x.Double, &x.Bool, &x.String, true, &x.UnionArray, false, nil, true, &x.AnythingMap, false, nil, true)
-	if err != nil {
-		return err
-	}
-	if object {
-	}
-	return nil
-}
-
-func (x *X) MarshalJSON() ([]byte, error) {
-	return marshalUnion(x.Integer, x.Double, x.Bool, x.String, x.UnionArray != nil, x.UnionArray, false, nil, x.AnythingMap != nil, x.AnythingMap, false, nil, true)
+func (x *TopLevelElement) MarshalJSON() ([]byte, error) {
+	return marshalUnion(x.Integer, x.Double, x.Bool, x.String, x.AnythingArray != nil, x.AnythingArray, x.A != nil, x.A, false, nil, false, nil, true)
 }
 
 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) {
diff --git a/base/schema-golang/test/inputs/schema/rust-cycle-breaker-union.schema/default/quicktype.go b/head/schema-golang/test/inputs/schema/rust-cycle-breaker-union.schema/default/quicktype.go
index 72242de..220b373 100644
--- a/base/schema-golang/test/inputs/schema/rust-cycle-breaker-union.schema/default/quicktype.go
+++ b/head/schema-golang/test/inputs/schema/rust-cycle-breaker-union.schema/default/quicktype.go
@@ -26,31 +26,26 @@ type TopLevel struct {
 	Value string `json:"value"`
 }
 
-type Node struct {
-	Next  *Next  `json:"next"`
-	Value string `json:"value"`
-}
-
 type Next struct {
-	Node   *Node
-	String *string
+	String   *string
+	TopLevel *TopLevel
 }
 
 func (x *Next) UnmarshalJSON(data []byte) error {
-	x.Node = nil
-	var c Node
+	x.TopLevel = nil
+	var c TopLevel
 	object, err := unmarshalUnion(data, nil, nil, nil, &x.String, false, nil, true, &c, false, nil, false, nil, true)
 	if err != nil {
 		return err
 	}
 	if object {
-		x.Node = &c
+		x.TopLevel = &c
 	}
 	return nil
 }
 
 func (x *Next) MarshalJSON() ([]byte, error) {
-	return marshalUnion(nil, nil, nil, x.String, false, nil, x.Node != nil, x.Node, false, nil, false, nil, true)
+	return marshalUnion(nil, nil, nil, x.String, false, nil, x.TopLevel != nil, x.TopLevel, false, nil, false, nil, true)
 }
 
 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) {
diff --git a/base/schema-haskell/test/inputs/schema/recursive-union-flattening.schema/default/QuickType.hs b/head/schema-haskell/test/inputs/schema/recursive-union-flattening.schema/default/QuickType.hs
index e460b28..4ecb397 100644
--- a/base/schema-haskell/test/inputs/schema/recursive-union-flattening.schema/default/QuickType.hs
+++ b/head/schema-haskell/test/inputs/schema/recursive-union-flattening.schema/default/QuickType.hs
@@ -3,11 +3,9 @@
 
 module QuickType
     ( QuickType (..)
-    , QuickTypeClass (..)
-    , XClass (..)
+    , A (..)
+    , PurpleQuickType (..)
     , QuickTypeElement (..)
-    , XElement (..)
-    , X (..)
     , decodeTopLevel
     ) where
 
@@ -27,44 +25,30 @@ data QuickType
     | UnionArrayInQuickType ([QuickTypeElement])
     deriving (Show)
 
+data PurpleQuickType
+    = AnythingMapInPurpleQuickType (HashMap Text Value)
+    | BoolInPurpleQuickType Bool
+    | DoubleInPurpleQuickType Float
+    | IntegerInPurpleQuickType Int
+    | NullInPurpleQuickType
+    | StringInPurpleQuickType Text
+    | UnionArrayInPurpleQuickType ([QuickTypeElement])
+    deriving (Show)
+
+data A = A
+    { xA :: Maybe PurpleQuickType
+    } deriving (Show)
+
 data QuickTypeElement
-    = AnythingArrayInQuickTypeElement ([Value])
+    = AInQuickTypeElement A
+    | AnythingArrayInQuickTypeElement ([Value])
     | BoolInQuickTypeElement Bool
     | DoubleInQuickTypeElement Float
     | IntegerInQuickTypeElement Int
     | NullInQuickTypeElement
-    | QuickTypeClassInQuickTypeElement QuickTypeClass
     | StringInQuickTypeElement Text
     deriving (Show)
 
-data QuickTypeClass = QuickTypeClass
-    { xQuickTypeClass :: Maybe X
-    } deriving (Show)
-
-data XClass = XClass
-    { xXClass :: Maybe X
-    } deriving (Show)
-
-data XElement
-    = AnythingArrayInXElement ([Value])
-    | BoolInXElement Bool
-    | DoubleInXElement Float
-    | IntegerInXElement Int
-    | NullInXElement
-    | StringInXElement Text
-    | XClassInXElement XClass
-    deriving (Show)
-
-data X
-    = AnythingMapInX (HashMap Text Value)
-    | BoolInX Bool
-    | DoubleInX Float
-    | IntegerInX Int
-    | NullInX
-    | StringInX Text
-    | UnionArrayInX ([XElement])
-    deriving (Show)
-
 decodeTopLevel :: ByteString -> Maybe QuickType
 decodeTopLevel = decode
 
@@ -86,76 +70,48 @@ instance FromJSON QuickType where
     parseJSON xs@(String _) = (fmap StringInQuickType . parseJSON) xs
     parseJSON xs@(Array _) = (fmap UnionArrayInQuickType . parseJSON) xs
 
+instance ToJSON PurpleQuickType where
+    toJSON (AnythingMapInPurpleQuickType x) = toJSON x
+    toJSON (BoolInPurpleQuickType x) = toJSON x
+    toJSON (DoubleInPurpleQuickType x) = toJSON x
+    toJSON (IntegerInPurpleQuickType x) = toJSON x
+    toJSON NullInPurpleQuickType = Null
+    toJSON (StringInPurpleQuickType x) = toJSON x
+    toJSON (UnionArrayInPurpleQuickType x) = toJSON x
+
+instance FromJSON PurpleQuickType where
+    parseJSON xs@(Object _) = (fmap AnythingMapInPurpleQuickType . parseJSON) xs
+    parseJSON xs@(Bool _) = (fmap BoolInPurpleQuickType . parseJSON) xs
+    parseJSON xs@(Number _) = (fmap DoubleInPurpleQuickType . parseJSON) xs
+    parseJSON xs@(Number _) = (fmap IntegerInPurpleQuickType . parseJSON) xs
+    parseJSON Null = return NullInPurpleQuickType
+    parseJSON xs@(String _) = (fmap StringInPurpleQuickType . parseJSON) xs
+    parseJSON xs@(Array _) = (fmap UnionArrayInPurpleQuickType . parseJSON) xs
+
+instance ToJSON A where
+    toJSON (A xA) =
+        object
+        [ "x" .= xA
+        ]
+
+instance FromJSON A where
+    parseJSON (Object v) = A
+        <$> v .:? "x"
+
 instance ToJSON QuickTypeElement where
+    toJSON (AInQuickTypeElement x) = toJSON x
     toJSON (AnythingArrayInQuickTypeElement x) = toJSON x
     toJSON (BoolInQuickTypeElement x) = toJSON x
     toJSON (DoubleInQuickTypeElement x) = toJSON x
     toJSON (IntegerInQuickTypeElement x) = toJSON x
     toJSON NullInQuickTypeElement = Null
-    toJSON (QuickTypeClassInQuickTypeElement x) = toJSON x
     toJSON (StringInQuickTypeElement x) = toJSON x
 
 instance FromJSON QuickTypeElement where
+    parseJSON xs@(Object _) = (fmap AInQuickTypeElement . parseJSON) xs
     parseJSON xs@(Array _) = (fmap AnythingArrayInQuickTypeElement . parseJSON) xs
     parseJSON xs@(Bool _) = (fmap BoolInQuickTypeElement . parseJSON) xs
     parseJSON xs@(Number _) = (fmap DoubleInQuickTypeElement . parseJSON) xs
     parseJSON xs@(Number _) = (fmap IntegerInQuickTypeElement . parseJSON) xs
     parseJSON Null = return NullInQuickTypeElement
-    parseJSON xs@(Object _) = (fmap QuickTypeClassInQuickTypeElement . parseJSON) xs
     parseJSON xs@(String _) = (fmap StringInQuickTypeElement . parseJSON) xs
-
-instance ToJSON QuickTypeClass where
-    toJSON (QuickTypeClass xQuickTypeClass) =
-        object
-        [ "x" .= xQuickTypeClass
-        ]
-
-instance FromJSON QuickTypeClass where
-    parseJSON (Object v) = QuickTypeClass
-        <$> v .:? "x"
-
-instance ToJSON XClass where
-    toJSON (XClass xXClass) =
-        object
-        [ "x" .= xXClass
-        ]
-
-instance FromJSON XClass where
-    parseJSON (Object v) = XClass
-        <$> v .:? "x"
-
-instance ToJSON XElement where
-    toJSON (AnythingArrayInXElement x) = toJSON x
-    toJSON (BoolInXElement x) = toJSON x
-    toJSON (DoubleInXElement x) = toJSON x
-    toJSON (IntegerInXElement x) = toJSON x
-    toJSON NullInXElement = Null
-    toJSON (StringInXElement x) = toJSON x
-    toJSON (XClassInXElement x) = toJSON x
-
-instance FromJSON XElement where
-    parseJSON xs@(Array _) = (fmap AnythingArrayInXElement . parseJSON) xs
-    parseJSON xs@(Bool _) = (fmap BoolInXElement . parseJSON) xs
-    parseJSON xs@(Number _) = (fmap DoubleInXElement . parseJSON) xs
-    parseJSON xs@(Number _) = (fmap IntegerInXElement . parseJSON) xs
-    parseJSON Null = return NullInXElement
-    parseJSON xs@(String _) = (fmap StringInXElement . parseJSON) xs
-    parseJSON xs@(Object _) = (fmap XClassInXElement . parseJSON) xs
-
-instance ToJSON X where
-    toJSON (AnythingMapInX x) = toJSON x
-    toJSON (BoolInX x) = toJSON x
-    toJSON (DoubleInX x) = toJSON x
-    toJSON (IntegerInX x) = toJSON x
-    toJSON NullInX = Null
-    toJSON (StringInX x) = toJSON x
-    toJSON (UnionArrayInX x) = toJSON x
-
-instance FromJSON X where
-    parseJSON xs@(Object _) = (fmap AnythingMapInX . parseJSON) xs
-    parseJSON xs@(Bool _) = (fmap BoolInX . parseJSON) xs
-    parseJSON xs@(Number _) = (fmap DoubleInX . parseJSON) xs
-    parseJSON xs@(Number _) = (fmap IntegerInX . parseJSON) xs
-    parseJSON Null = return NullInX
-    parseJSON xs@(String _) = (fmap StringInX . parseJSON) xs
-    parseJSON xs@(Array _) = (fmap UnionArrayInX . parseJSON) xs
diff --git a/base/schema-haskell/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.hs b/head/schema-haskell/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.hs
index 3362d54..c602583 100644
--- a/base/schema-haskell/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.hs
+++ b/head/schema-haskell/test/inputs/schema/rust-cycle-breaker-union.schema/default/QuickType.hs
@@ -3,7 +3,6 @@
 
 module QuickType
     ( QuickType (..)
-    , Node (..)
     , Next (..)
     , decodeTopLevel
     ) where
@@ -14,25 +13,30 @@ import Data.ByteString.Lazy (ByteString)
 import Data.HashMap.Strict (HashMap)
 import Data.Text (Text)
 
+data Next
+    = NullInNext
+    | QuickTypeInNext QuickType
+    | StringInNext Text
+    deriving (Show)
+
 data QuickType = QuickType
     { nextQuickType :: Maybe Next
     , valueQuickType :: Text
     } deriving (Show)
 
-data Node = Node
-    { nextNode :: Maybe Next
-    , valueNode :: Text
-    } deriving (Show)
-
-data Next
-    = NodeInNext Node
-    | NullInNext
-    | StringInNext Text
-    deriving (Show)
-
 decodeTopLevel :: ByteString -> Maybe QuickType
 decodeTopLevel = decode
 
+instance ToJSON Next where
+    toJSON NullInNext = Null
+    toJSON (QuickTypeInNext x) = toJSON x
+    toJSON (StringInNext x) = toJSON x
+
+instance FromJSON Next where
+    parseJSON Null = return NullInNext
+    parseJSON xs@(Object _) = (fmap QuickTypeInNext . parseJSON) xs
+    parseJSON xs@(String _) = (fmap StringInNext . parseJSON) xs
+
 instance ToJSON QuickType where
     toJSON (QuickType nextQuickType valueQuickType) =
         object
@@ -44,25 +48,3 @@ instance FromJSON QuickType where
     parseJSON (Object v) = QuickType
         <$> v .:? "next"
         <*> v .: "value"
-
-instance ToJSON Node where
-    toJSON (Node nextNode valueNode) =
-        object
-        [ "next" .= nextNode
-        , "value" .= valueNode
-        ]
-
-instance FromJSON Node where
-    parseJSON (Object v) = Node
-        <$> v .:? "next"
-        <*> v .: "value"
-
-instance ToJSON Next where
-    toJSON (NodeInNext x) = toJSON x
-    toJSON NullInNext = Null
-    toJSON (StringInNext x) = toJSON x
-
-instance FromJSON Next where
-    parseJSON xs@(Object _) = (fmap NodeInNext . parseJSON) xs
-    parseJSON Null = return NullInNext
-    parseJSON xs@(String _) = (fmap StringInNext . parseJSON) xs
diff --git a/head/schema-java/test/inputs/schema/recursive-ref-to-id.schema/default/src/main/java/io/quicktype/Converter.java b/head/schema-java/test/inputs/schema/recursive-ref-to-id.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/recursive-ref-to-id.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/recursive-ref-to-id.schema/default/src/main/java/io/quicktype/Data.java b/head/schema-java/test/inputs/schema/recursive-ref-to-id.schema/default/src/main/java/io/quicktype/Data.java
new file mode 100644
index 0000000..bcb52f6
--- /dev/null
+++ b/head/schema-java/test/inputs/schema/recursive-ref-to-id.schema/default/src/main/java/io/quicktype/Data.java
@@ -0,0 +1,12 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+
+public class Data {
+    private String id;
+
+    @JsonProperty("id")
+    public String getID() { return id; }
+    @JsonProperty("id")
+    public void setID(String value) { this.id = value; }
+}
diff --git a/head/schema-java/test/inputs/schema/recursive-ref-to-id.schema/default/src/main/java/io/quicktype/TopLevel.java b/head/schema-java/test/inputs/schema/recursive-ref-to-id.schema/default/src/main/java/io/quicktype/TopLevel.java
new file mode 100644
index 0000000..151df8d
--- /dev/null
+++ b/head/schema-java/test/inputs/schema/recursive-ref-to-id.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 List<TopLevel> children;
+    private Data data;
+
+    @JsonProperty("children")
+    public List<TopLevel> getChildren() { return children; }
+    @JsonProperty("children")
+    public void setChildren(List<TopLevel> value) { this.children = value; }
+
+    @JsonProperty("data")
+    public Data getData() { return data; }
+    @JsonProperty("data")
+    public void setData(Data value) { this.data = value; }
+}
diff --git a/head/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/A.java b/head/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/A.java
new file mode 100644
index 0000000..bfedcef
--- /dev/null
+++ b/head/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/A.java
@@ -0,0 +1,14 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+import java.util.List;
+import java.util.Map;
+
+public class A {
+    private PurpleTopLevel x;
+
+    @JsonProperty("x")
+    public PurpleTopLevel getX() { return x; }
+    @JsonProperty("x")
+    public void setX(PurpleTopLevel value) { this.x = value; }
+}
diff --git a/head/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/PurpleTopLevel.java b/head/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/PurpleTopLevel.java
new file mode 100644
index 0000000..e55faf3
--- /dev/null
+++ b/head/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/PurpleTopLevel.java
@@ -0,0 +1,85 @@
+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;
+import java.util.Map;
+
+@JsonDeserialize(using = PurpleTopLevel.Deserializer.class)
+@JsonSerialize(using = PurpleTopLevel.Serializer.class)
+public class PurpleTopLevel {
+    public Double doubleValue;
+    public Long integerValue;
+    public Boolean boolValue;
+    public List<TopLevelElement> unionArrayValue;
+    public Map<String, Object> anythingMapValue;
+    public String stringValue;
+
+    static class Deserializer extends JsonDeserializer<PurpleTopLevel> {
+        @Override
+        public PurpleTopLevel deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
+            PurpleTopLevel value = new PurpleTopLevel();
+            switch (jsonParser.currentToken()) {
+                case VALUE_NULL:
+                    break;
+                case VALUE_NUMBER_INT:
+                    value.integerValue = jsonParser.readValueAs(Long.class);
+                    break;
+                case VALUE_NUMBER_FLOAT:
+                    value.doubleValue = jsonParser.readValueAs(Double.class);
+                    break;
+                case VALUE_TRUE:
+                case VALUE_FALSE:
+                    value.boolValue = jsonParser.readValueAs(Boolean.class);
+                    break;
+                case VALUE_STRING:
+                    String string = jsonParser.readValueAs(String.class);
+                    value.stringValue = string;
+                    break;
+                case START_ARRAY:
+                    value.unionArrayValue = jsonParser.readValueAs(new TypeReference<List<TopLevelElement>>() {});
+                    break;
+                case START_OBJECT:
+                    value.anythingMapValue = jsonParser.readValueAs(Map.class);
+                    break;
+                default: throw new IOException("Cannot deserialize PurpleTopLevel");
+            }
+            return value;
+        }
+    }
+
+    static class Serializer extends JsonSerializer<PurpleTopLevel> {
+        @Override
+        public void serialize(PurpleTopLevel obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
+            if (obj.doubleValue != null) {
+                jsonGenerator.writeObject(obj.doubleValue);
+                return;
+            }
+            if (obj.integerValue != null) {
+                jsonGenerator.writeObject(obj.integerValue);
+                return;
+            }
+            if (obj.boolValue != null) {
+                jsonGenerator.writeObject(obj.boolValue);
+                return;
+            }
+            if (obj.unionArrayValue != null) {
+                jsonGenerator.writeObject(obj.unionArrayValue);
+                return;
+            }
+            if (obj.anythingMapValue != null) {
+                jsonGenerator.writeObject(obj.anythingMapValue);
+                return;
+            }
+            if (obj.stringValue != null) {
+                jsonGenerator.writeObject(obj.stringValue);
+                return;
+            }
+            jsonGenerator.writeNull();
+        }
+    }
+}
diff --git a/base/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelClass.java b/base/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelClass.java
deleted file mode 100644
index 945962b..0000000
--- a/base/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelClass.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package io.quicktype;
-
-import com.fasterxml.jackson.annotation.*;
-import java.util.List;
-import java.util.Map;
-
-public class TopLevelClass {
-    private X x;
-
-    @JsonProperty("x")
-    public X getX() { return x; }
-    @JsonProperty("x")
-    public void setX(X value) { this.x = value; }
-}
diff --git a/base/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelElement.java b/head/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelElement.java
index 7501a20..6a27c00 100644
--- a/base/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelElement.java
+++ b/head/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelElement.java
@@ -15,7 +15,7 @@ public class TopLevelElement {
     public Long integerValue;
     public Boolean boolValue;
     public List<Object> anythingArrayValue;
-    public TopLevelClass topLevelClassValue;
+    public A aValue;
     public String stringValue;
 
     static class Deserializer extends JsonDeserializer<TopLevelElement> {
@@ -43,7 +43,7 @@ public class TopLevelElement {
                     value.anythingArrayValue = jsonParser.readValueAs(new TypeReference<List<Object>>() {});
                     break;
                 case START_OBJECT:
-                    value.topLevelClassValue = jsonParser.readValueAs(TopLevelClass.class);
+                    value.aValue = jsonParser.readValueAs(A.class);
                     break;
                 default: throw new IOException("Cannot deserialize TopLevelElement");
             }
@@ -70,8 +70,8 @@ public class TopLevelElement {
                 jsonGenerator.writeObject(obj.anythingArrayValue);
                 return;
             }
-            if (obj.topLevelClassValue != null) {
-                jsonGenerator.writeObject(obj.topLevelClassValue);
+            if (obj.aValue != null) {
+                jsonGenerator.writeObject(obj.aValue);
                 return;
             }
             if (obj.stringValue != null) {
diff --git a/base/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/X.java b/base/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/X.java
deleted file mode 100644
index 7c62e8a..0000000
--- a/base/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/X.java
+++ /dev/null
@@ -1,85 +0,0 @@
-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;
-import java.util.Map;
-
-@JsonDeserialize(using = X.Deserializer.class)
-@JsonSerialize(using = X.Serializer.class)
-public class X {
-    public Double doubleValue;
-    public Long integerValue;
-    public Boolean boolValue;
-    public List<XElement> unionArrayValue;
-    public Map<String, Object> anythingMapValue;
-    public String stringValue;
-
-    static class Deserializer extends JsonDeserializer<X> {
-        @Override
-        public X deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
-            X value = new X();
-            switch (jsonParser.currentToken()) {
-                case VALUE_NULL:
-                    break;
-                case VALUE_NUMBER_INT:
-                    value.integerValue = jsonParser.readValueAs(Long.class);
-                    break;
-                case VALUE_NUMBER_FLOAT:
-                    value.doubleValue = jsonParser.readValueAs(Double.class);
-                    break;
-                case VALUE_TRUE:
-                case VALUE_FALSE:
-                    value.boolValue = jsonParser.readValueAs(Boolean.class);
-                    break;
-                case VALUE_STRING:
-                    String string = jsonParser.readValueAs(String.class);
-                    value.stringValue = string;
-                    break;
-                case START_ARRAY:
-                    value.unionArrayValue = jsonParser.readValueAs(new TypeReference<List<XElement>>() {});
-                    break;
-                case START_OBJECT:
-                    value.anythingMapValue = jsonParser.readValueAs(Map.class);
-                    break;
-                default: throw new IOException("Cannot deserialize X");
-            }
-            return value;
-        }
-    }
-
-    static class Serializer extends JsonSerializer<X> {
-        @Override
-        public void serialize(X obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
-            if (obj.doubleValue != null) {
-                jsonGenerator.writeObject(obj.doubleValue);
-                return;
-            }
-            if (obj.integerValue != null) {
-                jsonGenerator.writeObject(obj.integerValue);
-                return;
-            }
-            if (obj.boolValue != null) {
-                jsonGenerator.writeObject(obj.boolValue);
-                return;
-            }
-            if (obj.unionArrayValue != null) {
-                jsonGenerator.writeObject(obj.unionArrayValue);
-                return;
-            }
-            if (obj.anythingMapValue != null) {
-                jsonGenerator.writeObject(obj.anythingMapValue);
-                return;
-            }
-            if (obj.stringValue != null) {
-                jsonGenerator.writeObject(obj.stringValue);
-                return;
-            }
-            jsonGenerator.writeNull();
-        }
-    }
-}
diff --git a/base/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/XClass.java b/base/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/XClass.java
deleted file mode 100644
index 067c0ee..0000000
--- a/base/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/XClass.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package io.quicktype;
-
-import com.fasterxml.jackson.annotation.*;
-import java.util.List;
-import java.util.Map;
-
-public class XClass {
-    private X x;
-
-    @JsonProperty("x")
-    public X getX() { return x; }
-    @JsonProperty("x")
-    public void setX(X value) { this.x = value; }
-}
diff --git a/base/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/XElement.java b/base/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/XElement.java
deleted file mode 100644
index dfc153c..0000000
--- a/base/schema-java/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/XElement.java
+++ /dev/null
@@ -1,84 +0,0 @@
-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 = XElement.Deserializer.class)
-@JsonSerialize(using = XElement.Serializer.class)
-public class XElement {
-    public Double doubleValue;
-    public Long integerValue;
-    public Boolean boolValue;
-    public List<Object> anythingArrayValue;
-    public XClass xClassValue;
-    public String stringValue;
-
-    static class Deserializer extends JsonDeserializer<XElement> {
-        @Override
-        public XElement deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
-            XElement value = new XElement();
-            switch (jsonParser.currentToken()) {
-                case VALUE_NULL:
-                    break;
-                case VALUE_NUMBER_INT:
-                    value.integerValue = jsonParser.readValueAs(Long.class);
-                    break;
-                case VALUE_NUMBER_FLOAT:
-                    value.doubleValue = jsonParser.readValueAs(Double.class);
-                    break;
-                case VALUE_TRUE:
-                case VALUE_FALSE:
-                    value.boolValue = jsonParser.readValueAs(Boolean.class);
-                    break;
-                case VALUE_STRING:
-                    String string = jsonParser.readValueAs(String.class);
-                    value.stringValue = string;
-                    break;
-                case START_ARRAY:
-                    value.anythingArrayValue = jsonParser.readValueAs(new TypeReference<List<Object>>() {});
-                    break;
-                case START_OBJECT:
-                    value.xClassValue = jsonParser.readValueAs(XClass.class);
-                    break;
-                default: throw new IOException("Cannot deserialize XElement");
-            }
-            return value;
-        }
-    }
-
-    static class Serializer extends JsonSerializer<XElement> {
-        @Override
-        public void serialize(XElement obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
-            if (obj.doubleValue != null) {
-                jsonGenerator.writeObject(obj.doubleValue);
-                return;
-            }
-            if (obj.integerValue != null) {
-                jsonGenerator.writeObject(obj.integerValue);
-                return;
-            }
-            if (obj.boolValue != null) {
-                jsonGenerator.writeObject(obj.boolValue);
-                return;
-            }
-            if (obj.anythingArrayValue != null) {
-                jsonGenerator.writeObject(obj.anythingArrayValue);
-                return;
-            }
-            if (obj.xClassValue != null) {
-                jsonGenerator.writeObject(obj.xClassValue);
-                return;
-            }
-            if (obj.stringValue != null) {
-                jsonGenerator.writeObject(obj.stringValue);
-                return;
-            }
-            jsonGenerator.writeNull();
-        }
-    }
-}
diff --git a/base/schema-java/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Next.java b/head/schema-java/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Next.java
index c59c6d3..67c934f 100644
--- a/base/schema-java/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Next.java
+++ b/head/schema-java/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Next.java
@@ -10,7 +10,7 @@ import com.fasterxml.jackson.core.type.*;
 @JsonDeserialize(using = Next.Deserializer.class)
 @JsonSerialize(using = Next.Serializer.class)
 public class Next {
-    public Node nodeValue;
+    public TopLevel topLevelValue;
     public String stringValue;
 
     static class Deserializer extends JsonDeserializer<Next> {
@@ -25,7 +25,7 @@ public class Next {
                     value.stringValue = string;
                     break;
                 case START_OBJECT:
-                    value.nodeValue = jsonParser.readValueAs(Node.class);
+                    value.topLevelValue = jsonParser.readValueAs(TopLevel.class);
                     break;
                 default: throw new IOException("Cannot deserialize Next");
             }
@@ -36,8 +36,8 @@ public class Next {
     static class Serializer extends JsonSerializer<Next> {
         @Override
         public void serialize(Next obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
-            if (obj.nodeValue != null) {
-                jsonGenerator.writeObject(obj.nodeValue);
+            if (obj.topLevelValue != null) {
+                jsonGenerator.writeObject(obj.topLevelValue);
                 return;
             }
             if (obj.stringValue != null) {
diff --git a/base/schema-java/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Node.java b/base/schema-java/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Node.java
deleted file mode 100644
index f7fcf3b..0000000
--- a/base/schema-java/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Node.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package io.quicktype;
-
-import com.fasterxml.jackson.annotation.*;
-
-public class Node {
-    private Next next;
-    private String value;
-
-    @JsonProperty("next")
-    public Next getNext() { return next; }
-    @JsonProperty("next")
-    public void setNext(Next value) { this.next = value; }
-
-    @JsonProperty("value")
-    public String getValue() { return value; }
-    @JsonProperty("value")
-    public void setValue(String value) { this.value = value; }
-}
diff --git a/head/schema-java-datetime-legacy/test/inputs/schema/recursive-ref-to-id.schema/default/src/main/java/io/quicktype/Converter.java b/head/schema-java-datetime-legacy/test/inputs/schema/recursive-ref-to-id.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/recursive-ref-to-id.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/recursive-ref-to-id.schema/default/src/main/java/io/quicktype/Data.java b/head/schema-java-datetime-legacy/test/inputs/schema/recursive-ref-to-id.schema/default/src/main/java/io/quicktype/Data.java
new file mode 100644
index 0000000..bcb52f6
--- /dev/null
+++ b/head/schema-java-datetime-legacy/test/inputs/schema/recursive-ref-to-id.schema/default/src/main/java/io/quicktype/Data.java
@@ -0,0 +1,12 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+
+public class Data {
+    private String id;
+
+    @JsonProperty("id")
+    public String getID() { return id; }
+    @JsonProperty("id")
+    public void setID(String value) { this.id = value; }
+}
diff --git a/head/schema-java-datetime-legacy/test/inputs/schema/recursive-ref-to-id.schema/default/src/main/java/io/quicktype/TopLevel.java b/head/schema-java-datetime-legacy/test/inputs/schema/recursive-ref-to-id.schema/default/src/main/java/io/quicktype/TopLevel.java
new file mode 100644
index 0000000..151df8d
--- /dev/null
+++ b/head/schema-java-datetime-legacy/test/inputs/schema/recursive-ref-to-id.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 List<TopLevel> children;
+    private Data data;
+
+    @JsonProperty("children")
+    public List<TopLevel> getChildren() { return children; }
+    @JsonProperty("children")
+    public void setChildren(List<TopLevel> value) { this.children = value; }
+
+    @JsonProperty("data")
+    public Data getData() { return data; }
+    @JsonProperty("data")
+    public void setData(Data value) { this.data = value; }
+}
diff --git a/head/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/A.java b/head/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/A.java
new file mode 100644
index 0000000..bfedcef
--- /dev/null
+++ b/head/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/A.java
@@ -0,0 +1,14 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+import java.util.List;
+import java.util.Map;
+
+public class A {
+    private PurpleTopLevel x;
+
+    @JsonProperty("x")
+    public PurpleTopLevel getX() { return x; }
+    @JsonProperty("x")
+    public void setX(PurpleTopLevel value) { this.x = value; }
+}
diff --git a/head/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/PurpleTopLevel.java b/head/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/PurpleTopLevel.java
new file mode 100644
index 0000000..e55faf3
--- /dev/null
+++ b/head/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/PurpleTopLevel.java
@@ -0,0 +1,85 @@
+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;
+import java.util.Map;
+
+@JsonDeserialize(using = PurpleTopLevel.Deserializer.class)
+@JsonSerialize(using = PurpleTopLevel.Serializer.class)
+public class PurpleTopLevel {
+    public Double doubleValue;
+    public Long integerValue;
+    public Boolean boolValue;
+    public List<TopLevelElement> unionArrayValue;
+    public Map<String, Object> anythingMapValue;
+    public String stringValue;
+
+    static class Deserializer extends JsonDeserializer<PurpleTopLevel> {
+        @Override
+        public PurpleTopLevel deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
+            PurpleTopLevel value = new PurpleTopLevel();
+            switch (jsonParser.currentToken()) {
+                case VALUE_NULL:
+                    break;
+                case VALUE_NUMBER_INT:
+                    value.integerValue = jsonParser.readValueAs(Long.class);
+                    break;
+                case VALUE_NUMBER_FLOAT:
+                    value.doubleValue = jsonParser.readValueAs(Double.class);
+                    break;
+                case VALUE_TRUE:
+                case VALUE_FALSE:
+                    value.boolValue = jsonParser.readValueAs(Boolean.class);
+                    break;
+                case VALUE_STRING:
+                    String string = jsonParser.readValueAs(String.class);
+                    value.stringValue = string;
+                    break;
+                case START_ARRAY:
+                    value.unionArrayValue = jsonParser.readValueAs(new TypeReference<List<TopLevelElement>>() {});
+                    break;
+                case START_OBJECT:
+                    value.anythingMapValue = jsonParser.readValueAs(Map.class);
+                    break;
+                default: throw new IOException("Cannot deserialize PurpleTopLevel");
+            }
+            return value;
+        }
+    }
+
+    static class Serializer extends JsonSerializer<PurpleTopLevel> {
+        @Override
+        public void serialize(PurpleTopLevel obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
+            if (obj.doubleValue != null) {
+                jsonGenerator.writeObject(obj.doubleValue);
+                return;
+            }
+            if (obj.integerValue != null) {
+                jsonGenerator.writeObject(obj.integerValue);
+                return;
+            }
+            if (obj.boolValue != null) {
+                jsonGenerator.writeObject(obj.boolValue);
+                return;
+            }
+            if (obj.unionArrayValue != null) {
+                jsonGenerator.writeObject(obj.unionArrayValue);
+                return;
+            }
+            if (obj.anythingMapValue != null) {
+                jsonGenerator.writeObject(obj.anythingMapValue);
+                return;
+            }
+            if (obj.stringValue != null) {
+                jsonGenerator.writeObject(obj.stringValue);
+                return;
+            }
+            jsonGenerator.writeNull();
+        }
+    }
+}
diff --git a/base/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelClass.java b/base/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelClass.java
deleted file mode 100644
index 945962b..0000000
--- a/base/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelClass.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package io.quicktype;
-
-import com.fasterxml.jackson.annotation.*;
-import java.util.List;
-import java.util.Map;
-
-public class TopLevelClass {
-    private X x;
-
-    @JsonProperty("x")
-    public X getX() { return x; }
-    @JsonProperty("x")
-    public void setX(X value) { this.x = value; }
-}
diff --git a/base/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelElement.java b/head/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelElement.java
index 7501a20..6a27c00 100644
--- a/base/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelElement.java
+++ b/head/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelElement.java
@@ -15,7 +15,7 @@ public class TopLevelElement {
     public Long integerValue;
     public Boolean boolValue;
     public List<Object> anythingArrayValue;
-    public TopLevelClass topLevelClassValue;
+    public A aValue;
     public String stringValue;
 
     static class Deserializer extends JsonDeserializer<TopLevelElement> {
@@ -43,7 +43,7 @@ public class TopLevelElement {
                     value.anythingArrayValue = jsonParser.readValueAs(new TypeReference<List<Object>>() {});
                     break;
                 case START_OBJECT:
-                    value.topLevelClassValue = jsonParser.readValueAs(TopLevelClass.class);
+                    value.aValue = jsonParser.readValueAs(A.class);
                     break;
                 default: throw new IOException("Cannot deserialize TopLevelElement");
             }
@@ -70,8 +70,8 @@ public class TopLevelElement {
                 jsonGenerator.writeObject(obj.anythingArrayValue);
                 return;
             }
-            if (obj.topLevelClassValue != null) {
-                jsonGenerator.writeObject(obj.topLevelClassValue);
+            if (obj.aValue != null) {
+                jsonGenerator.writeObject(obj.aValue);
                 return;
             }
             if (obj.stringValue != null) {
diff --git a/base/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/X.java b/base/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/X.java
deleted file mode 100644
index 7c62e8a..0000000
--- a/base/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/X.java
+++ /dev/null
@@ -1,85 +0,0 @@
-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;
-import java.util.Map;
-
-@JsonDeserialize(using = X.Deserializer.class)
-@JsonSerialize(using = X.Serializer.class)
-public class X {
-    public Double doubleValue;
-    public Long integerValue;
-    public Boolean boolValue;
-    public List<XElement> unionArrayValue;
-    public Map<String, Object> anythingMapValue;
-    public String stringValue;
-
-    static class Deserializer extends JsonDeserializer<X> {
-        @Override
-        public X deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
-            X value = new X();
-            switch (jsonParser.currentToken()) {
-                case VALUE_NULL:
-                    break;
-                case VALUE_NUMBER_INT:
-                    value.integerValue = jsonParser.readValueAs(Long.class);
-                    break;
-                case VALUE_NUMBER_FLOAT:
-                    value.doubleValue = jsonParser.readValueAs(Double.class);
-                    break;
-                case VALUE_TRUE:
-                case VALUE_FALSE:
-                    value.boolValue = jsonParser.readValueAs(Boolean.class);
-                    break;
-                case VALUE_STRING:
-                    String string = jsonParser.readValueAs(String.class);
-                    value.stringValue = string;
-                    break;
-                case START_ARRAY:
-                    value.unionArrayValue = jsonParser.readValueAs(new TypeReference<List<XElement>>() {});
-                    break;
-                case START_OBJECT:
-                    value.anythingMapValue = jsonParser.readValueAs(Map.class);
-                    break;
-                default: throw new IOException("Cannot deserialize X");
-            }
-            return value;
-        }
-    }
-
-    static class Serializer extends JsonSerializer<X> {
-        @Override
-        public void serialize(X obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
-            if (obj.doubleValue != null) {
-                jsonGenerator.writeObject(obj.doubleValue);
-                return;
-            }
-            if (obj.integerValue != null) {
-                jsonGenerator.writeObject(obj.integerValue);
-                return;
-            }
-            if (obj.boolValue != null) {
-                jsonGenerator.writeObject(obj.boolValue);
-                return;
-            }
-            if (obj.unionArrayValue != null) {
-                jsonGenerator.writeObject(obj.unionArrayValue);
-                return;
-            }
-            if (obj.anythingMapValue != null) {
-                jsonGenerator.writeObject(obj.anythingMapValue);
-                return;
-            }
-            if (obj.stringValue != null) {
-                jsonGenerator.writeObject(obj.stringValue);
-                return;
-            }
-            jsonGenerator.writeNull();
-        }
-    }
-}
diff --git a/base/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/XClass.java b/base/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/XClass.java
deleted file mode 100644
index 067c0ee..0000000
--- a/base/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/XClass.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package io.quicktype;
-
-import com.fasterxml.jackson.annotation.*;
-import java.util.List;
-import java.util.Map;
-
-public class XClass {
-    private X x;
-
-    @JsonProperty("x")
-    public X getX() { return x; }
-    @JsonProperty("x")
-    public void setX(X value) { this.x = value; }
-}
diff --git a/base/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/XElement.java b/base/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/XElement.java
deleted file mode 100644
index dfc153c..0000000
--- a/base/schema-java-datetime-legacy/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/XElement.java
+++ /dev/null
@@ -1,84 +0,0 @@
-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 = XElement.Deserializer.class)
-@JsonSerialize(using = XElement.Serializer.class)
-public class XElement {
-    public Double doubleValue;
-    public Long integerValue;
-    public Boolean boolValue;
-    public List<Object> anythingArrayValue;
-    public XClass xClassValue;
-    public String stringValue;
-
-    static class Deserializer extends JsonDeserializer<XElement> {
-        @Override
-        public XElement deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
-            XElement value = new XElement();
-            switch (jsonParser.currentToken()) {
-                case VALUE_NULL:
-                    break;
-                case VALUE_NUMBER_INT:
-                    value.integerValue = jsonParser.readValueAs(Long.class);
-                    break;
-                case VALUE_NUMBER_FLOAT:
-                    value.doubleValue = jsonParser.readValueAs(Double.class);
-                    break;
-                case VALUE_TRUE:
-                case VALUE_FALSE:
-                    value.boolValue = jsonParser.readValueAs(Boolean.class);
-                    break;
-                case VALUE_STRING:
-                    String string = jsonParser.readValueAs(String.class);
-                    value.stringValue = string;
-                    break;
-                case START_ARRAY:
-                    value.anythingArrayValue = jsonParser.readValueAs(new TypeReference<List<Object>>() {});
-                    break;
-                case START_OBJECT:
-                    value.xClassValue = jsonParser.readValueAs(XClass.class);
-                    break;
-                default: throw new IOException("Cannot deserialize XElement");
-            }
-            return value;
-        }
-    }
-
-    static class Serializer extends JsonSerializer<XElement> {
-        @Override
-        public void serialize(XElement obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
-            if (obj.doubleValue != null) {
-                jsonGenerator.writeObject(obj.doubleValue);
-                return;
-            }
-            if (obj.integerValue != null) {
-                jsonGenerator.writeObject(obj.integerValue);
-                return;
-            }
-            if (obj.boolValue != null) {
-                jsonGenerator.writeObject(obj.boolValue);
-                return;
-            }
-            if (obj.anythingArrayValue != null) {
-                jsonGenerator.writeObject(obj.anythingArrayValue);
-                return;
-            }
-            if (obj.xClassValue != null) {
-                jsonGenerator.writeObject(obj.xClassValue);
-                return;
-            }
-            if (obj.stringValue != null) {
-                jsonGenerator.writeObject(obj.stringValue);
-                return;
-            }
-            jsonGenerator.writeNull();
-        }
-    }
-}
diff --git a/base/schema-java-datetime-legacy/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Next.java b/head/schema-java-datetime-legacy/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Next.java
index c59c6d3..67c934f 100644
--- a/base/schema-java-datetime-legacy/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Next.java
+++ b/head/schema-java-datetime-legacy/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Next.java
@@ -10,7 +10,7 @@ import com.fasterxml.jackson.core.type.*;
 @JsonDeserialize(using = Next.Deserializer.class)
 @JsonSerialize(using = Next.Serializer.class)
 public class Next {
-    public Node nodeValue;
+    public TopLevel topLevelValue;
     public String stringValue;
 
     static class Deserializer extends JsonDeserializer<Next> {
@@ -25,7 +25,7 @@ public class Next {
                     value.stringValue = string;
                     break;
                 case START_OBJECT:
-                    value.nodeValue = jsonParser.readValueAs(Node.class);
+                    value.topLevelValue = jsonParser.readValueAs(TopLevel.class);
                     break;
                 default: throw new IOException("Cannot deserialize Next");
             }
@@ -36,8 +36,8 @@ public class Next {
     static class Serializer extends JsonSerializer<Next> {
         @Override
         public void serialize(Next obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
-            if (obj.nodeValue != null) {
-                jsonGenerator.writeObject(obj.nodeValue);
+            if (obj.topLevelValue != null) {
+                jsonGenerator.writeObject(obj.topLevelValue);
                 return;
             }
             if (obj.stringValue != null) {
diff --git a/base/schema-java-datetime-legacy/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Node.java b/base/schema-java-datetime-legacy/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Node.java
deleted file mode 100644
index f7fcf3b..0000000
--- a/base/schema-java-datetime-legacy/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Node.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package io.quicktype;
-
-import com.fasterxml.jackson.annotation.*;
-
-public class Node {
-    private Next next;
-    private String value;
-
-    @JsonProperty("next")
-    public Next getNext() { return next; }
-    @JsonProperty("next")
-    public void setNext(Next value) { this.next = value; }
-
-    @JsonProperty("value")
-    public String getValue() { return value; }
-    @JsonProperty("value")
-    public void setValue(String value) { this.value = value; }
-}
diff --git a/head/schema-java-lombok/test/inputs/schema/recursive-ref-to-id.schema/default/src/main/java/io/quicktype/Converter.java b/head/schema-java-lombok/test/inputs/schema/recursive-ref-to-id.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/recursive-ref-to-id.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/recursive-ref-to-id.schema/default/src/main/java/io/quicktype/Data.java b/head/schema-java-lombok/test/inputs/schema/recursive-ref-to-id.schema/default/src/main/java/io/quicktype/Data.java
new file mode 100644
index 0000000..bcb52f6
--- /dev/null
+++ b/head/schema-java-lombok/test/inputs/schema/recursive-ref-to-id.schema/default/src/main/java/io/quicktype/Data.java
@@ -0,0 +1,12 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+
+public class Data {
+    private String id;
+
+    @JsonProperty("id")
+    public String getID() { return id; }
+    @JsonProperty("id")
+    public void setID(String value) { this.id = value; }
+}
diff --git a/head/schema-java-lombok/test/inputs/schema/recursive-ref-to-id.schema/default/src/main/java/io/quicktype/TopLevel.java b/head/schema-java-lombok/test/inputs/schema/recursive-ref-to-id.schema/default/src/main/java/io/quicktype/TopLevel.java
new file mode 100644
index 0000000..151df8d
--- /dev/null
+++ b/head/schema-java-lombok/test/inputs/schema/recursive-ref-to-id.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 List<TopLevel> children;
+    private Data data;
+
+    @JsonProperty("children")
+    public List<TopLevel> getChildren() { return children; }
+    @JsonProperty("children")
+    public void setChildren(List<TopLevel> value) { this.children = value; }
+
+    @JsonProperty("data")
+    public Data getData() { return data; }
+    @JsonProperty("data")
+    public void setData(Data value) { this.data = value; }
+}
diff --git a/head/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/A.java b/head/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/A.java
new file mode 100644
index 0000000..bfedcef
--- /dev/null
+++ b/head/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/A.java
@@ -0,0 +1,14 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+import java.util.List;
+import java.util.Map;
+
+public class A {
+    private PurpleTopLevel x;
+
+    @JsonProperty("x")
+    public PurpleTopLevel getX() { return x; }
+    @JsonProperty("x")
+    public void setX(PurpleTopLevel value) { this.x = value; }
+}
diff --git a/head/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/PurpleTopLevel.java b/head/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/PurpleTopLevel.java
new file mode 100644
index 0000000..e55faf3
--- /dev/null
+++ b/head/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/PurpleTopLevel.java
@@ -0,0 +1,85 @@
+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;
+import java.util.Map;
+
+@JsonDeserialize(using = PurpleTopLevel.Deserializer.class)
+@JsonSerialize(using = PurpleTopLevel.Serializer.class)
+public class PurpleTopLevel {
+    public Double doubleValue;
+    public Long integerValue;
+    public Boolean boolValue;
+    public List<TopLevelElement> unionArrayValue;
+    public Map<String, Object> anythingMapValue;
+    public String stringValue;
+
+    static class Deserializer extends JsonDeserializer<PurpleTopLevel> {
+        @Override
+        public PurpleTopLevel deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
+            PurpleTopLevel value = new PurpleTopLevel();
+            switch (jsonParser.currentToken()) {
+                case VALUE_NULL:
+                    break;
+                case VALUE_NUMBER_INT:
+                    value.integerValue = jsonParser.readValueAs(Long.class);
+                    break;
+                case VALUE_NUMBER_FLOAT:
+                    value.doubleValue = jsonParser.readValueAs(Double.class);
+                    break;
+                case VALUE_TRUE:
+                case VALUE_FALSE:
+                    value.boolValue = jsonParser.readValueAs(Boolean.class);
+                    break;
+                case VALUE_STRING:
+                    String string = jsonParser.readValueAs(String.class);
+                    value.stringValue = string;
+                    break;
+                case START_ARRAY:
+                    value.unionArrayValue = jsonParser.readValueAs(new TypeReference<List<TopLevelElement>>() {});
+                    break;
+                case START_OBJECT:
+                    value.anythingMapValue = jsonParser.readValueAs(Map.class);
+                    break;
+                default: throw new IOException("Cannot deserialize PurpleTopLevel");
+            }
+            return value;
+        }
+    }
+
+    static class Serializer extends JsonSerializer<PurpleTopLevel> {
+        @Override
+        public void serialize(PurpleTopLevel obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
+            if (obj.doubleValue != null) {
+                jsonGenerator.writeObject(obj.doubleValue);
+                return;
+            }
+            if (obj.integerValue != null) {
+                jsonGenerator.writeObject(obj.integerValue);
+                return;
+            }
+            if (obj.boolValue != null) {
+                jsonGenerator.writeObject(obj.boolValue);
+                return;
+            }
+            if (obj.unionArrayValue != null) {
+                jsonGenerator.writeObject(obj.unionArrayValue);
+                return;
+            }
+            if (obj.anythingMapValue != null) {
+                jsonGenerator.writeObject(obj.anythingMapValue);
+                return;
+            }
+            if (obj.stringValue != null) {
+                jsonGenerator.writeObject(obj.stringValue);
+                return;
+            }
+            jsonGenerator.writeNull();
+        }
+    }
+}
diff --git a/base/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelClass.java b/base/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelClass.java
deleted file mode 100644
index 945962b..0000000
--- a/base/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelClass.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package io.quicktype;
-
-import com.fasterxml.jackson.annotation.*;
-import java.util.List;
-import java.util.Map;
-
-public class TopLevelClass {
-    private X x;
-
-    @JsonProperty("x")
-    public X getX() { return x; }
-    @JsonProperty("x")
-    public void setX(X value) { this.x = value; }
-}
diff --git a/base/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelElement.java b/head/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelElement.java
index 7501a20..6a27c00 100644
--- a/base/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelElement.java
+++ b/head/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/TopLevelElement.java
@@ -15,7 +15,7 @@ public class TopLevelElement {
     public Long integerValue;
     public Boolean boolValue;
     public List<Object> anythingArrayValue;
-    public TopLevelClass topLevelClassValue;
+    public A aValue;
     public String stringValue;
 
     static class Deserializer extends JsonDeserializer<TopLevelElement> {
@@ -43,7 +43,7 @@ public class TopLevelElement {
                     value.anythingArrayValue = jsonParser.readValueAs(new TypeReference<List<Object>>() {});
                     break;
                 case START_OBJECT:
-                    value.topLevelClassValue = jsonParser.readValueAs(TopLevelClass.class);
+                    value.aValue = jsonParser.readValueAs(A.class);
                     break;
                 default: throw new IOException("Cannot deserialize TopLevelElement");
             }
@@ -70,8 +70,8 @@ public class TopLevelElement {
                 jsonGenerator.writeObject(obj.anythingArrayValue);
                 return;
             }
-            if (obj.topLevelClassValue != null) {
-                jsonGenerator.writeObject(obj.topLevelClassValue);
+            if (obj.aValue != null) {
+                jsonGenerator.writeObject(obj.aValue);
                 return;
             }
             if (obj.stringValue != null) {
diff --git a/base/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/X.java b/base/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/X.java
deleted file mode 100644
index 7c62e8a..0000000
--- a/base/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/X.java
+++ /dev/null
@@ -1,85 +0,0 @@
-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;
-import java.util.Map;
-
-@JsonDeserialize(using = X.Deserializer.class)
-@JsonSerialize(using = X.Serializer.class)
-public class X {
-    public Double doubleValue;
-    public Long integerValue;
-    public Boolean boolValue;
-    public List<XElement> unionArrayValue;
-    public Map<String, Object> anythingMapValue;
-    public String stringValue;
-
-    static class Deserializer extends JsonDeserializer<X> {
-        @Override
-        public X deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
-            X value = new X();
-            switch (jsonParser.currentToken()) {
-                case VALUE_NULL:
-                    break;
-                case VALUE_NUMBER_INT:
-                    value.integerValue = jsonParser.readValueAs(Long.class);
-                    break;
-                case VALUE_NUMBER_FLOAT:
-                    value.doubleValue = jsonParser.readValueAs(Double.class);
-                    break;
-                case VALUE_TRUE:
-                case VALUE_FALSE:
-                    value.boolValue = jsonParser.readValueAs(Boolean.class);
-                    break;
-                case VALUE_STRING:
-                    String string = jsonParser.readValueAs(String.class);
-                    value.stringValue = string;
-                    break;
-                case START_ARRAY:
-                    value.unionArrayValue = jsonParser.readValueAs(new TypeReference<List<XElement>>() {});
-                    break;
-                case START_OBJECT:
-                    value.anythingMapValue = jsonParser.readValueAs(Map.class);
-                    break;
-                default: throw new IOException("Cannot deserialize X");
-            }
-            return value;
-        }
-    }
-
-    static class Serializer extends JsonSerializer<X> {
-        @Override
-        public void serialize(X obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
-            if (obj.doubleValue != null) {
-                jsonGenerator.writeObject(obj.doubleValue);
-                return;
-            }
-            if (obj.integerValue != null) {
-                jsonGenerator.writeObject(obj.integerValue);
-                return;
-            }
-            if (obj.boolValue != null) {
-                jsonGenerator.writeObject(obj.boolValue);
-                return;
-            }
-            if (obj.unionArrayValue != null) {
-                jsonGenerator.writeObject(obj.unionArrayValue);
-                return;
-            }
-            if (obj.anythingMapValue != null) {
-                jsonGenerator.writeObject(obj.anythingMapValue);
-                return;
-            }
-            if (obj.stringValue != null) {
-                jsonGenerator.writeObject(obj.stringValue);
-                return;
-            }
-            jsonGenerator.writeNull();
-        }
-    }
-}
diff --git a/base/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/XClass.java b/base/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/XClass.java
deleted file mode 100644
index 067c0ee..0000000
--- a/base/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/XClass.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package io.quicktype;
-
-import com.fasterxml.jackson.annotation.*;
-import java.util.List;
-import java.util.Map;
-
-public class XClass {
-    private X x;
-
-    @JsonProperty("x")
-    public X getX() { return x; }
-    @JsonProperty("x")
-    public void setX(X value) { this.x = value; }
-}
diff --git a/base/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/XElement.java b/base/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/XElement.java
deleted file mode 100644
index dfc153c..0000000
--- a/base/schema-java-lombok/test/inputs/schema/recursive-union-flattening.schema/default/src/main/java/io/quicktype/XElement.java
+++ /dev/null
@@ -1,84 +0,0 @@
-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 = XElement.Deserializer.class)
-@JsonSerialize(using = XElement.Serializer.class)
-public class XElement {
-    public Double doubleValue;
-    public Long integerValue;
-    public Boolean boolValue;
-    public List<Object> anythingArrayValue;
-    public XClass xClassValue;
-    public String stringValue;
-
-    static class Deserializer extends JsonDeserializer<XElement> {
-        @Override
-        public XElement deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
-            XElement value = new XElement();
-            switch (jsonParser.currentToken()) {
-                case VALUE_NULL:
-                    break;
-                case VALUE_NUMBER_INT:
-                    value.integerValue = jsonParser.readValueAs(Long.class);
-                    break;
-                case VALUE_NUMBER_FLOAT:
-                    value.doubleValue = jsonParser.readValueAs(Double.class);
-                    break;
-                case VALUE_TRUE:
-                case VALUE_FALSE:
-                    value.boolValue = jsonParser.readValueAs(Boolean.class);
-                    break;
-                case VALUE_STRING:
-                    String string = jsonParser.readValueAs(String.class);
-                    value.stringValue = string;
-                    break;
-                case START_ARRAY:
-                    value.anythingArrayValue = jsonParser.readValueAs(new TypeReference<List<Object>>() {});
-                    break;
-                case START_OBJECT:
-                    value.xClassValue = jsonParser.readValueAs(XClass.class);
-                    break;
-                default: throw new IOException("Cannot deserialize XElement");
-            }
-            return value;
-        }
-    }
-
-    static class Serializer extends JsonSerializer<XElement> {
-        @Override
-        public void serialize(XElement obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
-            if (obj.doubleValue != null) {
-                jsonGenerator.writeObject(obj.doubleValue);
-                return;
-            }
-            if (obj.integerValue != null) {
-                jsonGenerator.writeObject(obj.integerValue);
-                return;
-            }
-            if (obj.boolValue != null) {
-                jsonGenerator.writeObject(obj.boolValue);
-                return;
-            }
-            if (obj.anythingArrayValue != null) {
-                jsonGenerator.writeObject(obj.anythingArrayValue);
-                return;
-            }
-            if (obj.xClassValue != null) {
-                jsonGenerator.writeObject(obj.xClassValue);
-                return;
-            }
-            if (obj.stringValue != null) {
-                jsonGenerator.writeObject(obj.stringValue);
-                return;
-            }
-            jsonGenerator.writeNull();
-        }
-    }
-}
diff --git a/base/schema-java-lombok/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Next.java b/head/schema-java-lombok/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Next.java
index c59c6d3..67c934f 100644
--- a/base/schema-java-lombok/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Next.java
+++ b/head/schema-java-lombok/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Next.java
@@ -10,7 +10,7 @@ import com.fasterxml.jackson.core.type.*;
 @JsonDeserialize(using = Next.Deserializer.class)
 @JsonSerialize(using = Next.Serializer.class)
 public class Next {
-    public Node nodeValue;
+    public TopLevel topLevelValue;
     public String stringValue;
 
     static class Deserializer extends JsonDeserializer<Next> {
@@ -25,7 +25,7 @@ public class Next {
                     value.stringValue = string;
                     break;
                 case START_OBJECT:
-                    value.nodeValue = jsonParser.readValueAs(Node.class);
+                    value.topLevelValue = jsonParser.readValueAs(TopLevel.class);
                     break;
                 default: throw new IOException("Cannot deserialize Next");
             }
@@ -36,8 +36,8 @@ public class Next {
     static class Serializer extends JsonSerializer<Next> {
         @Override
         public void serialize(Next obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
-            if (obj.nodeValue != null) {
-                jsonGenerator.writeObject(obj.nodeValue);
+            if (obj.topLevelValue != null) {
+                jsonGenerator.writeObject(obj.topLevelValue);
                 return;
             }
             if (obj.stringValue != null) {
diff --git a/base/schema-java-lombok/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Node.java b/base/schema-java-lombok/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Node.java
deleted file mode 100644
index f7fcf3b..0000000
--- a/base/schema-java-lombok/test/inputs/schema/rust-cycle-breaker-union.schema/default/src/main/java/io/quicktype/Node.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package io.quicktype;
-
-import com.fasterxml.jackson.annotation.*;
-
-public class Node {
-    private Next next;
-    private String value;
-
-    @JsonProperty("next")
-    public Next getNext() { return next; }
-    @JsonProperty("next")
-    public void setNext(Next value) { this.next = value; }
-
-    @JsonProperty("value")
-    public String getValue() { return value; }
-    @JsonProperty("value")
-    public void setValue(String value) { this.value = value; }
-}
diff --git a/head/schema-javascript/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.js b/head/schema-javascript/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.js
new file mode 100644
index 0000000..c799ac4
--- /dev/null
+++ b/head/schema-javascript/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.js
@@ -0,0 +1,186 @@
+// 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: "children", js: "children", typ: u(undefined, a(r("TopLevel"))) },
+        { json: "data", js: "data", typ: u(undefined, r("Data")) },
+    ], "any"),
+    "Data": o([
+        { json: "id", js: "id", typ: u(undefined, "") },
+    ], "any"),
+};
+
+module.exports = {
+    "topLevelToJson": topLevelToJson,
+    "toTopLevel": toTopLevel,
+};
diff --git a/base/schema-javascript/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.js b/head/schema-javascript/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.js
index 85cec11..ab1fb5f 100644
--- a/base/schema-javascript/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.js
+++ b/head/schema-javascript/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.js
@@ -10,11 +10,11 @@
 // Converts JSON strings to/from your types
 // and asserts the results of JSON.parse at runtime
 function toTopLevel(json) {
-    return cast(JSON.parse(json), u(a(u(a("any"), true, 3.14, null, r("TopLevelObject"), "")), true, 3.14, 0, m("any"), null, ""));
+    return cast(JSON.parse(json), u(a(u(a("any"), true, 3.14, null, r("A"), "")), true, 3.14, 0, m("any"), null, ""));
 }
 
 function topLevelToJson(value) {
-    return JSON.stringify(uncast(value, u(a(u(a("any"), true, 3.14, null, r("TopLevelObject"), "")), true, 3.14, 0, m("any"), null, "")), null, 2);
+    return JSON.stringify(uncast(value, u(a(u(a("any"), true, 3.14, null, r("A"), "")), true, 3.14, 0, m("any"), null, "")), null, 2);
 }
 
 function invalidValue(typ, val, key, parent = '') {
@@ -171,11 +171,8 @@ function r(name) {
 }
 
 const typeMap = {
-    "TopLevelObject": o([
-        { json: "x", js: "x", typ: u(undefined, u(a(u(a("any"), true, 3.14, null, r("XObject"), "")), true, 3.14, m("any"), null, "")) },
-    ], "any"),
-    "XObject": o([
-        { json: "x", js: "x", typ: u(undefined, u(a(u(a("any"), true, 3.14, null, r("XObject"), "")), true, 3.14, m("any"), null, "")) },
+    "A": o([
+        { json: "x", js: "x", typ: u(undefined, u(a(u(a("any"), true, 3.14, null, r("A"), "")), true, 3.14, m("any"), null, "")) },
     ], "any"),
 };
 
diff --git a/base/schema-javascript/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.js b/head/schema-javascript/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.js
index 9a76089..bc832be 100644
--- a/base/schema-javascript/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.js
+++ b/head/schema-javascript/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.js
@@ -172,11 +172,7 @@ function r(name) {
 
 const typeMap = {
     "TopLevel": o([
-        { json: "next", js: "next", typ: u(undefined, u(null, r("Node"), "")) },
-        { json: "value", js: "value", typ: "" },
-    ], "any"),
-    "Node": o([
-        { json: "next", js: "next", typ: u(undefined, u(null, r("Node"), "")) },
+        { json: "next", js: "next", typ: u(undefined, u(null, r("TopLevel"), "")) },
         { json: "value", js: "value", typ: "" },
     ], "any"),
 };
diff --git a/head/schema-kotlin/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.kt b/head/schema-kotlin/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.kt
new file mode 100644
index 0000000..5838964
--- /dev/null
+++ b/head/schema-kotlin/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.kt
@@ -0,0 +1,24 @@
+// To parse the JSON, install Klaxon and do:
+//
+//   val topLevel = TopLevel.fromJson(jsonString)
+
+package quicktype
+
+import com.beust.klaxon.*
+
+private val klaxon = Klaxon()
+
+data class TopLevel (
+    val children: List<TopLevel>? = null,
+    val data: Data? = null
+) {
+    public fun toJson() = klaxon.toJsonString(this)
+
+    companion object {
+        public fun fromJson(json: String) = klaxon.parse<TopLevel>(json)
+    }
+}
+
+data class Data (
+    val id: String? = null
+)
diff --git a/base/schema-kotlin/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.kt b/head/schema-kotlin/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.kt
index e91f58c..d2d2ece 100644
--- a/base/schema-kotlin/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.kt
+++ b/head/schema-kotlin/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.kt
@@ -17,39 +17,34 @@ private fun <T> Klaxon.convert(k: kotlin.reflect.KClass<*>, fromJson: (JsonValue
 private val klaxon = Klaxon()
     .convert(Next::class, { Next.fromJson(it) }, { it.toJson() }, true)
 
-data class TopLevel (
-    val next: Next? = null,
-    val value: String
-) {
-    public fun toJson() = klaxon.toJsonString(this)
-
-    companion object {
-        public fun fromJson(json: String) = klaxon.parse<TopLevel>(json)
-    }
-}
-
-data class Node (
-    val next: Next? = null,
-    val value: String
-)
-
 sealed class Next {
-    class NodeValue(val value: Node)     : Next()
-    class StringValue(val value: String) : Next()
-    class NullValue()                    : Next()
+    class StringValue(val value: String)     : Next()
+    class TopLevelValue(val value: TopLevel) : Next()
+    class NullValue()                        : Next()
 
     public fun toJson(): String = klaxon.toJsonString(when (this) {
-        is NodeValue   -> this.value
-        is StringValue -> this.value
-        is NullValue   -> "null"
+        is StringValue   -> this.value
+        is TopLevelValue -> this.value
+        is NullValue     -> "null"
     })
 
     companion object {
         public fun fromJson(jv: JsonValue): Next = when (jv.inside) {
-            is JsonObject -> NodeValue(jv.obj?.let { klaxon.parseFromJsonObject<Node>(it) }!!)
             is String     -> StringValue(jv.string!!)
+            is JsonObject -> TopLevelValue(jv.obj?.let { klaxon.parseFromJsonObject<TopLevel>(it) }!!)
             null          -> NullValue()
             else          -> throw IllegalArgumentException()
         }
     }
 }
+
+data class TopLevel (
+    val next: Next? = null,
+    val value: String
+) {
+    public fun toJson() = klaxon.toJsonString(this)
+
+    companion object {
+        public fun fromJson(json: String) = klaxon.parse<TopLevel>(json)
+    }
+}
diff --git a/head/schema-kotlin-jackson/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.kt b/head/schema-kotlin-jackson/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.kt
new file mode 100644
index 0000000..8d188a8
--- /dev/null
+++ b/head/schema-kotlin-jackson/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.kt
@@ -0,0 +1,34 @@
+// 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.*
+
+val mapper = jacksonObjectMapper().apply {
+    propertyNamingStrategy = PropertyNamingStrategy.LOWER_CAMEL_CASE
+    setSerializationInclusion(JsonInclude.Include.NON_NULL)
+}
+
+data class TopLevel (
+    val children: List<TopLevel>? = null,
+    val data: Data? = null
+) {
+    fun toJson() = mapper.writeValueAsString(this)
+
+    companion object {
+        fun fromJson(json: String) = mapper.readValue<TopLevel>(json)
+    }
+}
+
+data class Data (
+    val id: String? = null
+)
diff --git a/base/schema-kotlin-jackson/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.kt b/head/schema-kotlin-jackson/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.kt
index fc0ceff..7120f32 100644
--- a/base/schema-kotlin-jackson/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.kt
+++ b/head/schema-kotlin-jackson/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.kt
@@ -30,43 +30,36 @@ val mapper = jacksonObjectMapper().apply {
     convert(Next::class, { Next.fromJson(it) }, { it.toJson() }, true)
 }
 
-data class TopLevel (
-    val next: Next? = null,
+sealed class Next {
+    class StringValue(val value: String)     : Next()
+    class TopLevelValue(val value: TopLevel) : Next()
+    class NullValue()                        : Next()
 
-    @get:JsonProperty(required=true)@field:JsonProperty(required=true)
-    val value: String
-) {
-    fun toJson() = mapper.writeValueAsString(this)
+    fun toJson(): String = mapper.writeValueAsString(when (this) {
+        is StringValue   -> this.value
+        is TopLevelValue -> this.value
+        is NullValue     -> "null"
+    })
 
     companion object {
-        fun fromJson(json: String) = mapper.readValue<TopLevel>(json)
+        fun fromJson(jn: JsonNode): Next = when (jn) {
+            is TextNode   -> StringValue(mapper.treeToValue(jn))
+            is ObjectNode -> TopLevelValue(mapper.treeToValue(jn))
+            null          -> NullValue()
+            else          -> throw IllegalArgumentException()
+        }
     }
 }
 
-data class Node (
+data class TopLevel (
     val next: Next? = null,
 
     @get:JsonProperty(required=true)@field:JsonProperty(required=true)
     val value: String
-)
-
-sealed class Next {
-    class NodeValue(val value: Node)     : Next()
-    class StringValue(val value: String) : Next()
-    class NullValue()                    : Next()
-
-    fun toJson(): String = mapper.writeValueAsString(when (this) {
-        is NodeValue   -> this.value
-        is StringValue -> this.value
-        is NullValue   -> "null"
-    })
+) {
+    fun toJson() = mapper.writeValueAsString(this)
 
     companion object {
-        fun fromJson(jn: JsonNode): Next = when (jn) {
-            is ObjectNode -> NodeValue(mapper.treeToValue(jn))
-            is TextNode   -> StringValue(mapper.treeToValue(jn))
-            null          -> NullValue()
-            else          -> throw IllegalArgumentException()
-        }
+        fun fromJson(json: String) = mapper.readValue<TopLevel>(json)
     }
 }
diff --git a/head/schema-kotlinx/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.kt b/head/schema-kotlinx/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.kt
new file mode 100644
index 0000000..79f6c84
--- /dev/null
+++ b/head/schema-kotlinx/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.kt
@@ -0,0 +1,22 @@
+// To parse the JSON, install kotlin's serialization plugin and do:
+//
+// val json     = Json { allowStructuredMapKeys = true }
+// val topLevel = json.parse(TopLevel.serializer(), jsonString)
+
+package quicktype
+
+import kotlinx.serialization.*
+import kotlinx.serialization.json.*
+import kotlinx.serialization.descriptors.*
+import kotlinx.serialization.encoding.*
+
+@Serializable
+data class TopLevel (
+    val children: List<TopLevel>? = null,
+    val data: Data? = null
+)
+
+@Serializable
+data class Data (
+    val id: String? = null
+)
diff --git a/head/schema-php/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.php b/head/schema-php/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.php
new file mode 100644
index 0000000..0df93b2
--- /dev/null
+++ b/head/schema-php/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.php
@@ -0,0 +1,295 @@
+<?php
+declare(strict_types=1);
+
+// This is an autogenerated file:TopLevel
+
+class TopLevel {
+    private ?array $children; // json:children Optional
+    private ?Data $data; // json:data Optional
+
+    /**
+     * @param array|null $children
+     * @param Data|null $data
+     */
+    public function __construct(?array $children, ?Data $data) {
+        $this->children = $children;
+        $this->data = $data;
+    }
+
+    /**
+     * @param ?array $value
+     * @throws Exception
+     * @return ?array
+     */
+    public static function fromChildren(?array $value): ?array {
+        if (!is_null($value)) {
+            return  array_map(function ($value) {
+                return TopLevel::from($value); /*class*/
+            }, $value);
+        } else {
+            return  null;
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return ?array
+     */
+    public function toChildren(): ?array {
+        if (TopLevel::validateChildren($this->children))  {
+            if (!is_null($this->children)) {
+                return array_map(function ($value) {
+                    return $value->to(); /*class*/
+                }, $this->children);
+            } else {
+                return  null;
+            }
+        }
+        throw new Exception('never get to this TopLevel::children');
+    }
+
+    /**
+     * @param array|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateChildren(?array $value): bool {
+        if (!is_null($value)) {
+            if (!is_array($value)) {
+                throw new Exception("Attribute Error:TopLevel::children");
+            }
+            array_walk($value, function($value_v) {
+                $value_v->validate();
+            });
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return ?array
+     */
+    public function getChildren(): ?array {
+        if (TopLevel::validateChildren($this->children))  {
+            return $this->children;
+        }
+        throw new Exception('never get to getChildren TopLevel::children');
+    }
+
+    /**
+     * @return ?array
+     */
+    public static function sampleChildren(): ?array {
+        return  array(
+            TopLevel::sample() /*31:*/
+        ); /* 31:children*/
+    }
+
+    /**
+     * @param ?stdClass $value
+     * @throws Exception
+     * @return ?Data
+     */
+    public static function fromData(?stdClass $value): ?Data {
+        if (!is_null($value)) {
+            return Data::from($value); /*class*/
+        } else {
+            return  null;
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return ?stdClass
+     */
+    public function toData(): ?stdClass {
+        if (TopLevel::validateData($this->data))  {
+            if (!is_null($this->data)) {
+                return $this->data->to(); /*class*/
+            } else {
+                return  null;
+            }
+        }
+        throw new Exception('never get to this TopLevel::data');
+    }
+
+    /**
+     * @param Data|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateData(?Data $value): bool {
+        if (!is_null($value)) {
+            $value->validate();
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return ?Data
+     */
+    public function getData(): ?Data {
+        if (TopLevel::validateData($this->data))  {
+            return $this->data;
+        }
+        throw new Exception('never get to getData TopLevel::data');
+    }
+
+    /**
+     * @return ?Data
+     */
+    public static function sampleData(): ?Data {
+        return Data::sample(); /*32:data*/
+    }
+
+    /**
+     * @throws Exception
+     * @return bool
+     */
+    public function validate(): bool {
+        return TopLevel::validateChildren($this->children)
+        || TopLevel::validateData($this->data);
+    }
+
+    /**
+     * @return stdClass
+     * @throws Exception
+     */
+    public function to(): stdClass  {
+        $out = new stdClass();
+        $out->{'children'} = $this->toChildren();
+        $out->{'data'} = $this->toData();
+        return $out;
+    }
+
+    /**
+     * @param stdClass $obj
+     * @return TopLevel
+     * @throws Exception
+     */
+    public static function from(stdClass $obj): TopLevel {
+        return new TopLevel(
+         TopLevel::fromChildren($obj->{'children'})
+        ,TopLevel::fromData($obj->{'data'})
+        );
+    }
+
+    /**
+     * @return TopLevel
+     */
+    public static function sample(): TopLevel {
+        return new TopLevel(
+         TopLevel::sampleChildren()
+        ,TopLevel::sampleData()
+        );
+    }
+}
+
+// This is an autogenerated file:Data
+
+class Data {
+    private ?string $id; // json:id Optional
+
+    /**
+     * @param string|null $id
+     */
+    public function __construct(?string $id) {
+        $this->id = $id;
+    }
+
+    /**
+     * @param ?string $value
+     * @throws Exception
+     * @return ?string
+     */
+    public static function fromID(?string $value): ?string {
+        if (!is_null($value)) {
+            return $value; /*string*/
+        } else {
+            return  null;
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return ?string
+     */
+    public function toID(): ?string {
+        if (Data::validateID($this->id))  {
+            if (!is_null($this->id)) {
+                return $this->id; /*string*/
+            } else {
+                return  null;
+            }
+        }
+        throw new Exception('never get to this Data::id');
+    }
+
+    /**
+     * @param string|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateID(?string $value): bool {
+        if (!is_null($value)) {
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return ?string
+     */
+    public function getID(): ?string {
+        if (Data::validateID($this->id))  {
+            return $this->id;
+        }
+        throw new Exception('never get to getID Data::id');
+    }
+
+    /**
+     * @return ?string
+     */
+    public static function sampleID(): ?string {
+        return 'Data::id::31'; /*31:id*/
+    }
+
+    /**
+     * @throws Exception
+     * @return bool
+     */
+    public function validate(): bool {
+        return Data::validateID($this->id);
+    }
+
+    /**
+     * @return stdClass
+     * @throws Exception
+     */
+    public function to(): stdClass  {
+        $out = new stdClass();
+        $out->{'id'} = $this->toID();
+        return $out;
+    }
+
+    /**
+     * @param stdClass $obj
+     * @return Data
+     * @throws Exception
+     */
+    public static function from(stdClass $obj): Data {
+        return new Data(
+         Data::fromID($obj->{'id'})
+        );
+    }
+
+    /**
+     * @return Data
+     */
+    public static function sample(): Data {
+        return new Data(
+         Data::sampleID()
+        );
+    }
+}
diff --git a/base/schema-php/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.php b/head/schema-php/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.php
index 899c0ef..bc67cdb 100644
--- a/base/schema-php/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.php
+++ b/head/schema-php/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.php
@@ -4,14 +4,14 @@ declare(strict_types=1);
 // This is an autogenerated file:TopLevel
 
 class TopLevel {
-    private Node|string|null $next; // json:next Optional
+    private TopLevel|string|null $next; // json:next Optional
     private string $value; // json:value Required
 
     /**
-     * @param Node|string|null $next
+     * @param TopLevel|string|null $next
      * @param string $value
      */
-    public function __construct(Node|string|null $next, string $value) {
+    public function __construct(TopLevel|string|null $next, string $value) {
         $this->next = $next;
         $this->value = $value;
     }
@@ -19,13 +19,13 @@ class TopLevel {
     /**
      * @param stdClass|string|null $value
      * @throws Exception
-     * @return Node|string|null
+     * @return TopLevel|string|null
      */
-    public static function fromNext(stdClass|string|null $value): Node|string|null {
+    public static function fromNext(stdClass|string|null $value): TopLevel|string|null {
         if (is_null($value)) {
             return $value; /*null*/
         } elseif (is_object($value)) {
-            return Node::from($value); /*class*/
+            return TopLevel::from($value); /*class*/
         } elseif (is_string($value)) {
             return $value; /*string*/
         } else {
@@ -41,7 +41,7 @@ class TopLevel {
         if (TopLevel::validateNext($this->next))  {
             if (is_null($this->next)) {
                 return $this->next; /*null*/
-            } elseif ($this->next instanceof Node) {
+            } elseif ($this->next instanceof TopLevel) {
                 return $this->next->to(); /*class*/
             } elseif (is_string($this->next)) {
                 return $this->next; /*string*/
@@ -53,16 +53,16 @@ class TopLevel {
     }
 
     /**
-     * @param Node|string|null
+     * @param TopLevel|string|null
      * @return bool
      * @throws Exception
      */
-    public static function validateNext(Node|string|null $value): bool {
+    public static function validateNext(TopLevel|string|null $value): bool {
         if (is_null($value)) {
             if (!is_null($value)) {
                 throw new Exception("Attribute Error:TopLevel::next");
             }
-        } elseif ($value instanceof Node) {
+        } elseif ($value instanceof TopLevel) {
             $value->validate();
         } elseif (is_string($value)) {
             if (!is_string($value)) {
@@ -76,9 +76,9 @@ class TopLevel {
 
     /**
      * @throws Exception
-     * @return Node|string|null
+     * @return TopLevel|string|null
      */
-    public function getNext(): Node|string|null {
+    public function getNext(): TopLevel|string|null {
         if (TopLevel::validateNext($this->next))  {
             return $this->next;
         }
@@ -86,10 +86,10 @@ class TopLevel {
     }
 
     /**
-     * @return Node|string|null
+     * @return TopLevel|string|null
      */
-    public static function sampleNext(): Node|string|null {
-        return Node::sample(); /*31:next*/
+    public static function sampleNext(): TopLevel|string|null {
+        return TopLevel::sample(); /*31:next*/
     }
 
     /**
@@ -181,184 +181,3 @@ class TopLevel {
         );
     }
 }
-
-// This is an autogenerated file:Node
-
-class Node {
-    private Node|string|null $next; // json:next Optional
-    private string $value; // json:value Required
-
-    /**
-     * @param Node|string|null $next
-     * @param string $value
-     */
-    public function __construct(Node|string|null $next, string $value) {
-        $this->next = $next;
-        $this->value = $value;
-    }
-
-    /**
-     * @param stdClass|string|null $value
-     * @throws Exception
-     * @return Node|string|null
-     */
-    public static function fromNext(stdClass|string|null $value): Node|string|null {
-        if (is_null($value)) {
-            return $value; /*null*/
-        } elseif (is_object($value)) {
-            return Node::from($value); /*class*/
-        } elseif (is_string($value)) {
-            return $value; /*string*/
-        } else {
-            throw new Exception('Cannot deserialize union value in Node');
-        }
-    }
-
-    /**
-     * @throws Exception
-     * @return stdClass|string|null
-     */
-    public function toNext(): stdClass|string|null {
-        if (Node::validateNext($this->next))  {
-            if (is_null($this->next)) {
-                return $this->next; /*null*/
-            } elseif ($this->next instanceof Node) {
-                return $this->next->to(); /*class*/
-            } elseif (is_string($this->next)) {
-                return $this->next; /*string*/
-            } else {
-                throw new Exception('Union value has no matching member in Node');
-            }
-        }
-        throw new Exception('never get to this Node::next');
-    }
-
-    /**
-     * @param Node|string|null
-     * @return bool
-     * @throws Exception
-     */
-    public static function validateNext(Node|string|null $value): bool {
-        if (is_null($value)) {
-            if (!is_null($value)) {
-                throw new Exception("Attribute Error:Node::next");
-            }
-        } elseif ($value instanceof Node) {
-            $value->validate();
-        } elseif (is_string($value)) {
-            if (!is_string($value)) {
-                throw new Exception("Attribute Error:Node::next");
-            }
-        } else {
-            throw new Exception("Attribute Error:Node::next");
-        }
-        return true;
-    }
-
-    /**
-     * @throws Exception
-     * @return Node|string|null
-     */
-    public function getNext(): Node|string|null {
-        if (Node::validateNext($this->next))  {
-            return $this->next;
-        }
-        throw new Exception('never get to getNext Node::next');
-    }
-
-    /**
-     * @return Node|string|null
-     */
-    public static function sampleNext(): Node|string|null {
-        return Node::sample(); /*31:next*/
-    }
-
-    /**
-     * @param string $value
-     * @throws Exception
-     * @return string
-     */
-    public static function fromValue(string $value): string {
-        return $value; /*string*/
-    }
-
-    /**
-     * @throws Exception
-     * @return string
-     */
-    public function toValue(): string {
-        if (Node::validateValue($this->value))  {
-            return $this->value; /*string*/
-        }
-        throw new Exception('never get to this Node::value');
-    }
-
-    /**
-     * @param string
-     * @return bool
-     * @throws Exception
-     */
-    public static function validateValue(string $value): bool {
-        return true;
-    }
-
-    /**
-     * @throws Exception
-     * @return string
-     */
-    public function getValue(): string {
-        if (Node::validateValue($this->value))  {
-            return $this->value;
-        }
-        throw new Exception('never get to getValue Node::value');
-    }
-
-    /**
-     * @return string
-     */
-    public static function sampleValue(): string {
-        return 'Node::value::32'; /*32:value*/
-    }
-
-    /**
-     * @throws Exception
-     * @return bool
-     */
-    public function validate(): bool {
-        return Node::validateNext($this->next)
-        || Node::validateValue($this->value);
-    }
-
-    /**
-     * @return stdClass
-     * @throws Exception
-     */
-    public function to(): stdClass  {
-        $out = new stdClass();
-        $out->{'next'} = $this->toNext();
-        $out->{'value'} = $this->toValue();
-        return $out;
-    }
-
-    /**
-     * @param stdClass $obj
-     * @return Node
-     * @throws Exception
-     */
-    public static function from(stdClass $obj): Node {
-        return new Node(
-         Node::fromNext($obj->{'next'})
-        ,Node::fromValue($obj->{'value'})
-        );
-    }
-
-    /**
-     * @return Node
-     */
-    public static function sample(): Node {
-        return new Node(
-         Node::sampleNext()
-        ,Node::sampleValue()
-        );
-    }
-}
diff --git a/head/schema-pike/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.pmod b/head/schema-pike/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.pmod
new file mode 100644
index 0000000..fbc1328
--- /dev/null
+++ b/head/schema-pike/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.pmod
@@ -0,0 +1,56 @@
+// 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 {
+    array(TopLevel)|mixed children; // json: "children"
+    Data|mixed            data;     // json: "data"
+
+    string encode_json() {
+        mapping(string:mixed) json = ([
+            "children" : children,
+            "data" : data,
+        ]);
+
+        return Standards.JSON.encode(json);
+    }
+}
+
+TopLevel TopLevel_from_JSON(mixed json) {
+    TopLevel retval = TopLevel();
+
+    retval.children = json["children"];
+    retval.data = json["data"];
+
+    return retval;
+}
+
+class Data {
+    mixed|string id; // json: "id"
+
+    string encode_json() {
+        mapping(string:mixed) json = ([
+            "id" : id,
+        ]);
+
+        return Standards.JSON.encode(json);
+    }
+}
+
+Data Data_from_JSON(mixed json) {
+    Data retval = Data();
+
+    retval.id = json["id"];
+
+    return retval;
+}
diff --git a/base/schema-pike/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.pmod b/head/schema-pike/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.pmod
index 67ca889..fde8f7e 100644
--- a/base/schema-pike/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.pmod
+++ b/head/schema-pike/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.pmod
@@ -18,34 +18,14 @@ TopLevel TopLevel_from_JSON(mixed json) {
     return json;
 }
 
-typedef array(mixed)|bool|float|string|TopLevelClass TopLevelElement;
+typedef mapping(string:mixed)|bool|float|string|array(TopLevelElement) PurpleTopLevel;
 
-TopLevelElement TopLevelElement_from_JSON(mixed json) {
+PurpleTopLevel PurpleTopLevel_from_JSON(mixed json) {
     return json;
 }
 
-class TopLevelClass {
-    X x; // json: "x"
-
-    string encode_json() {
-        mapping(string:mixed) json = ([
-            "x" : x,
-        ]);
-
-        return Standards.JSON.encode(json);
-    }
-}
-
-TopLevelClass TopLevelClass_from_JSON(mixed json) {
-    TopLevelClass retval = TopLevelClass();
-
-    retval.x = json["x"];
-
-    return retval;
-}
-
-class XClass {
-    X x; // json: "x"
+class A {
+    PurpleTopLevel x; // json: "x"
 
     string encode_json() {
         mapping(string:mixed) json = ([
@@ -56,22 +36,16 @@ class XClass {
     }
 }
 
-XClass XClass_from_JSON(mixed json) {
-    XClass retval = XClass();
+A A_from_JSON(mixed json) {
+    A retval = A();
 
     retval.x = json["x"];
 
     return retval;
 }
 
-typedef array(mixed)|bool|float|string|XClass XElement;
+typedef A|array(mixed)|bool|float|string TopLevelElement;
 
-XElement XElement_from_JSON(mixed json) {
-    return json;
-}
-
-typedef mapping(string:mixed)|bool|float|string|array(XElement) X;
-
-X X_from_JSON(mixed json) {
+TopLevelElement TopLevelElement_from_JSON(mixed json) {
     return json;
 }
diff --git a/base/schema-pike/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.pmod b/head/schema-pike/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.pmod
index 24107bc..8104716 100644
--- a/base/schema-pike/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.pmod
+++ b/head/schema-pike/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.pmod
@@ -12,30 +12,13 @@
 // 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 {
-    Next   next;  // json: "next"
-    string value; // json: "value"
-
-    string encode_json() {
-        mapping(string:mixed) json = ([
-            "next" : next,
-            "value" : value,
-        ]);
-
-        return Standards.JSON.encode(json);
-    }
-}
-
-TopLevel TopLevel_from_JSON(mixed json) {
-    TopLevel retval = TopLevel();
-
-    retval.next = json["next"];
-    retval.value = json["value"];
+typedef string|TopLevel Next;
 
-    return retval;
+Next Next_from_JSON(mixed json) {
+    return json;
 }
 
-class Node {
+class TopLevel {
     Next   next;  // json: "next"
     string value; // json: "value"
 
@@ -49,17 +32,11 @@ class Node {
     }
 }
 
-Node Node_from_JSON(mixed json) {
-    Node retval = Node();
+TopLevel TopLevel_from_JSON(mixed json) {
+    TopLevel retval = TopLevel();
 
     retval.next = json["next"];
     retval.value = json["value"];
 
     return retval;
 }
-
-typedef Node|string Next;
-
-Next Next_from_JSON(mixed json) {
-    return json;
-}
diff --git a/head/schema-python/test/inputs/schema/recursive-ref-to-id.schema/default/quicktype.py b/head/schema-python/test/inputs/schema/recursive-ref-to-id.schema/default/quicktype.py
new file mode 100644
index 0000000..2b2516f
--- /dev/null
+++ b/head/schema-python/test/inputs/schema/recursive-ref-to-id.schema/default/quicktype.py
@@ -0,0 +1,80 @@
+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_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 Data:
+    id: str | None = None
+
+    @staticmethod
+    def from_dict(obj: Any) -> 'Data':
+        assert isinstance(obj, dict)
+        id = from_union([from_str, from_none], obj.get("id"))
+        return Data(id)
+
+    def to_dict(self) -> dict:
+        result: dict = {}
+        if self.id is not None:
+            result["id"] = from_union([from_str, from_none], self.id)
+        return result
+
+
+@dataclass
+class TopLevel:
+    children: 'list[TopLevel] | None' = None
+    data: Data | None = None
+
+    @staticmethod
+    def from_dict(obj: Any) -> 'TopLevel':
+        assert isinstance(obj, dict)
+        children = from_union([lambda x: from_list(TopLevel.from_dict, x), from_none], obj.get("children"))
+        data = from_union([Data.from_dict, from_none], obj.get("data"))
+        return TopLevel(children, data)
+
+    def to_dict(self) -> dict:
+        result: dict = {}
+        if self.children is not None:
+            result["children"] = from_union([lambda x: from_list(lambda x: to_class(TopLevel, x), x), from_none], self.children)
+        if self.data is not None:
+            result["data"] = from_union([lambda x: to_class(Data, x), from_none], self.data)
+        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/base/schema-python/test/inputs/schema/recursive-union-flattening.schema/default/quicktype.py b/head/schema-python/test/inputs/schema/recursive-union-flattening.schema/default/quicktype.py
index be6c208..989cf78 100644
--- a/base/schema-python/test/inputs/schema/recursive-union-flattening.schema/default/quicktype.py
+++ b/head/schema-python/test/inputs/schema/recursive-union-flattening.schema/default/quicktype.py
@@ -60,42 +60,25 @@ def to_class(c: Type[T], x: Any) -> dict:
 
 
 @dataclass
-class XClass:
-    x: 'float | int | bool | list[float | int | bool | list[Any] | XClass | str | None] | dict[str, Any] | str | None' = None
+class A:
+    x: 'float | int | bool | list[float | int | bool | list[Any] | A | str | None] | dict[str, Any] | str | None' = None
 
     @staticmethod
-    def from_dict(obj: Any) -> 'XClass':
+    def from_dict(obj: Any) -> 'A':
         assert isinstance(obj, dict)
-        x = from_union([from_none, from_int, from_float, from_bool, lambda x: from_list(lambda x: from_union([from_none, from_int, from_float, from_bool, lambda x: from_list(lambda x: x, x), XClass.from_dict, from_str], x), x), lambda x: from_dict(lambda x: x, x), from_str], obj.get("x"))
-        return XClass(x)
+        x = from_union([from_none, from_int, from_float, from_bool, lambda x: from_list(lambda x: from_union([from_none, from_int, from_float, from_bool, lambda x: from_list(lambda x: x, x), A.from_dict, from_str], x), x), lambda x: from_dict(lambda x: x, x), from_str], obj.get("x"))
+        return A(x)
 
     def to_dict(self) -> dict:
         result: dict = {}
         if self.x is not None:
-            result["x"] = from_union([from_none, from_int, to_float, from_bool, lambda x: from_list(lambda x: from_union([from_none, from_int, to_float, from_bool, lambda x: from_list(lambda x: x, x), lambda x: to_class(XClass, x), from_str], x), x), lambda x: from_dict(lambda x: x, x), from_str], self.x)
+            result["x"] = from_union([from_none, from_int, to_float, from_bool, lambda x: from_list(lambda x: from_union([from_none, from_int, to_float, from_bool, lambda x: from_list(lambda x: x, x), lambda x: to_class(A, x), from_str], x), x), lambda x: from_dict(lambda x: x, x), from_str], self.x)
         return result
 
 
-@dataclass
-class TopLevelClass:
-    x: float | int | bool | list[float | int | bool | list[Any] | XClass | str | None] | dict[str, Any] | str | None = None
-
-    @staticmethod
-    def from_dict(obj: Any) -> 'TopLevelClass':
-        assert isinstance(obj, dict)
-        x = from_union([from_none, from_int, from_float, from_bool, lambda x: from_list(lambda x: from_union([from_none, from_int, from_float, from_bool, lambda x: from_list(lambda x: x, x), XClass.from_dict, from_str], x), x), lambda x: from_dict(lambda x: x, x), from_str], obj.get("x"))
-        return TopLevelClass(x)
-
-    def to_dict(self) -> dict:
-        result: dict = {}
-        if self.x is not None:
-            result["x"] = from_union([from_none, from_int, to_float, from_bool, lambda x: from_list(lambda x: from_union([from_none, from_int, to_float, from_bool, lambda x: from_list(lambda x: x, x), lambda x: to_class(XClass, x), from_str], x), x), lambda x: from_dict(lambda x: x, x), from_str], self.x)
-        return result
-
-
-def top_level_from_dict(s: Any) -> float | int | bool | str | list[float | int | bool | list[Any] | TopLevelClass | str | None] | dict[str, Any] | None:
-    return from_union([from_none, from_int, from_float, from_bool, from_str, lambda x: from_list(lambda x: from_union([from_none, from_int, from_float, from_bool, lambda x: from_list(lambda x: x, x), TopLevelClass.from_dict, from_str], x), x), lambda x: from_dict(lambda x: x, x)], s)
+def top_level_from_dict(s: Any) -> float | int | bool | str | list[float | int | bool | list[Any] | A | str | None] | dict[str, Any] | None:
+    return from_union([from_none, from_int, from_float, from_bool, from_str, lambda x: from_list(lambda x: from_union([from_none, from_int, from_float, from_bool, lambda x: from_list(lambda x: x, x), A.from_dict, from_str], x), x), lambda x: from_dict(lambda x: x, x)], s)
 
 
-def top_level_to_dict(x: float | int | bool | str | list[float | int | bool | list[Any] | TopLevelClass | str | None] | dict[str, Any] | None) -> Any:
-    return from_union([from_none, from_int, to_float, from_bool, from_str, lambda x: from_list(lambda x: from_union([from_none, from_int, to_float, from_bool, lambda x: from_list(lambda x: x, x), lambda x: to_class(TopLevelClass, x), from_str], x), x), lambda x: from_dict(lambda x: x, x)], x)
+def top_level_to_dict(x: float | int | bool | str | list[float | int | bool | list[Any] | A | str | None] | dict[str, Any] | None) -> Any:
+    return from_union([from_none, from_int, to_float, from_bool, from_str, lambda x: from_list(lambda x: from_union([from_none, from_int, to_float, from_bool, lambda x: from_list(lambda x: x, x), lambda x: to_class(A, x), from_str], x), x), lambda x: from_dict(lambda x: x, x)], x)
diff --git a/base/schema-python/test/inputs/schema/rust-cycle-breaker-union.schema/default/quicktype.py b/head/schema-python/test/inputs/schema/rust-cycle-breaker-union.schema/default/quicktype.py
index 07e7d1b..52b9136 100644
--- a/base/schema-python/test/inputs/schema/rust-cycle-breaker-union.schema/default/quicktype.py
+++ b/head/schema-python/test/inputs/schema/rust-cycle-breaker-union.schema/default/quicktype.py
@@ -29,43 +29,23 @@ def to_class(c: Type[T], x: Any) -> dict:
     return cast(Any, x).to_dict()
 
 
-@dataclass
-class Node:
-    value: str
-    next: 'Node | str | None' = None
-
-    @staticmethod
-    def from_dict(obj: Any) -> 'Node':
-        assert isinstance(obj, dict)
-        value = from_str(obj.get("value"))
-        next = from_union([Node.from_dict, from_none, from_str], obj.get("next"))
-        return Node(value, next)
-
-    def to_dict(self) -> dict:
-        result: dict = {}
-        result["value"] = from_str(self.value)
-        if self.next is not None:
-            result["next"] = from_union([lambda x: to_class(Node, x), from_none, from_str], self.next)
-        return result
-
-
 @dataclass
 class TopLevel:
     value: str
-    next: Node | str | None = None
+    next: 'TopLevel | str | None' = None
 
     @staticmethod
     def from_dict(obj: Any) -> 'TopLevel':
         assert isinstance(obj, dict)
         value = from_str(obj.get("value"))
-        next = from_union([Node.from_dict, from_none, from_str], obj.get("next"))
+        next = from_union([TopLevel.from_dict, from_none, from_str], obj.get("next"))
         return TopLevel(value, next)
 
     def to_dict(self) -> dict:
         result: dict = {}
         result["value"] = from_str(self.value)
         if self.next is not None:
-            result["next"] = from_union([lambda x: to_class(Node, x), from_none, from_str], self.next)
+            result["next"] = from_union([lambda x: to_class(TopLevel, x), from_none, from_str], self.next)
         return result
 
 
diff --git a/head/schema-ruby/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.rb b/head/schema-ruby/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.rb
new file mode 100644
index 0000000..6391f0e
--- /dev/null
+++ b/head/schema-ruby/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.rb
@@ -0,0 +1,73 @@
+# 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.data&.id
+#
+# 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)
+
+  Hash   = Strict::Hash
+  String = Strict::String
+end
+
+class DataClass < Dry::Struct
+  attribute :id, Types::String.optional
+
+  def self.from_dynamic!(d)
+    d = Types::Hash[d]
+    new(
+      id: d["id"],
+    )
+  end
+
+  def self.from_json!(json)
+    from_dynamic!(JSON.parse(json))
+  end
+
+  def to_dynamic
+    {
+      "id" => id,
+    }
+  end
+
+  def to_json(options = nil)
+    JSON.generate(to_dynamic, options)
+  end
+end
+
+class TopLevel < Dry::Struct
+  attribute :children, Types.Array(TopLevel).optional
+  attribute :data,     DataClass.optional
+
+  def self.from_dynamic!(d)
+    d = Types::Hash[d]
+    new(
+      children: d["children"]&.map { |x| TopLevel.from_dynamic!(x) },
+      data:     d["data"] ? DataClass.from_dynamic!(d["data"]) : nil,
+    )
+  end
+
+  def self.from_json!(json)
+    from_dynamic!(JSON.parse(json))
+  end
+
+  def to_dynamic
+    {
+      "children" => children&.map { |x| x.to_dynamic },
+      "data"     => data&.to_dynamic,
+    }
+  end
+
+  def to_json(options = nil)
+    JSON.generate(to_dynamic, options)
+  end
+end
diff --git a/base/schema-ruby/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.rb b/head/schema-ruby/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.rb
index a5d73b7..f879099 100644
--- a/base/schema-ruby/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.rb
+++ b/head/schema-ruby/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.rb
@@ -24,15 +24,15 @@ module Types
 end
 
 # (forward declaration)
-class XClass < Dry::Struct; end
+class A < Dry::Struct; end
 
-class X < Dry::Struct
+class TopLevel1 < Dry::Struct
   attribute :anything_map, Types::Hash.meta(of: Types::Any).optional
   attribute :bool,         Types::Bool.optional
   attribute :double,       Types::Double.optional
   attribute :null,         Types::Nil.optional
   attribute :string,       Types::String.optional
-  attribute :union_array,  Types.Array(Types.Instance(XElement)).optional
+  attribute :union_array,  Types.Array(Types.Instance(TopLevelElement)).optional
 
   def self.from_dynamic!(d)
     begin
@@ -55,7 +55,7 @@ class X < Dry::Struct
       return new(string: d, union_array: nil, bool: nil, double: nil, anything_map: nil, null: nil)
     end
     begin
-      value = d.map { |x| XElement.from_dynamic!(x) }
+      value = d.map { |x| TopLevelElement.from_dynamic!(x) }
       if schema[:union_array].right.valid? value
         return new(union_array: value, bool: nil, double: nil, anything_map: nil, null: nil, string: nil)
       end
@@ -89,36 +89,36 @@ class X < Dry::Struct
   end
 end
 
-class XElement < Dry::Struct
+class TopLevelElement < Dry::Struct
+  attribute :a,              A.optional
   attribute :anything_array, Types.Array(Types::Any).optional
   attribute :bool,           Types::Bool.optional
   attribute :double,         Types::Double.optional
   attribute :null,           Types::Nil.optional
   attribute :string,         Types::String.optional
-  attribute :x_class,        XClass.optional
 
   def self.from_dynamic!(d)
+    begin
+      value = A.from_dynamic!(d)
+      if schema[:a].right.valid? value
+        return new(a: value, anything_array: nil, bool: nil, double: nil, null: nil, string: nil)
+      end
+    rescue
+    end
     if schema[:anything_array].right.valid? d
-      return new(anything_array: d, bool: nil, x_class: nil, double: nil, null: nil, string: nil)
+      return new(anything_array: d, bool: nil, a: nil, double: nil, null: nil, string: nil)
     end
     if schema[:bool].right.valid? d
-      return new(bool: d, anything_array: nil, x_class: nil, double: nil, null: nil, string: nil)
+      return new(bool: d, anything_array: nil, a: nil, double: nil, null: nil, string: nil)
     end
     if schema[:double].right.valid? d
-      return new(double: d, anything_array: nil, bool: nil, x_class: nil, null: nil, string: nil)
+      return new(double: d, anything_array: nil, bool: nil, a: nil, null: nil, string: nil)
     end
     if schema[:null].right.valid? d
-      return new(null: d, anything_array: nil, bool: nil, x_class: nil, double: nil, string: nil)
+      return new(null: d, anything_array: nil, bool: nil, a: nil, double: nil, string: nil)
     end
     if schema[:string].right.valid? d
-      return new(string: d, anything_array: nil, bool: nil, x_class: nil, double: nil, null: nil)
-    end
-    begin
-      value = XClass.from_dynamic!(d)
-      if schema[:x_class].right.valid? value
-        return new(x_class: value, anything_array: nil, bool: nil, double: nil, null: nil, string: nil)
-      end
-    rescue
+      return new(string: d, anything_array: nil, bool: nil, a: nil, double: nil, null: nil)
     end
     raise "Invalid union"
   end
@@ -128,7 +128,9 @@ class XElement < Dry::Struct
   end
 
   def to_dynamic
-    if anything_array != nil
+    if a != nil
+      a.to_dynamic
+    elsif anything_array != nil
       anything_array
     elsif bool != nil
       bool
@@ -136,8 +138,6 @@ class XElement < Dry::Struct
       double
     elsif string != nil
       string
-    elsif x_class != nil
-      x_class.to_dynamic
     else
       nil
     end
@@ -148,38 +148,13 @@ class XElement < Dry::Struct
   end
 end
 
-class XClass < Dry::Struct
-  attribute :x, Types.Instance(X).optional
-
-  def self.from_dynamic!(d)
-    d = Types::Hash[d]
-    new(
-      x: d["x"] ? X.from_dynamic!(d["x"]) : nil,
-    )
-  end
-
-  def self.from_json!(json)
-    from_dynamic!(JSON.parse(json))
-  end
-
-  def to_dynamic
-    {
-      "x" => x&.to_dynamic,
-    }
-  end
-
-  def to_json(options = nil)
-    JSON.generate(to_dynamic, options)
-  end
-end
-
-class TopLevelClass < Dry::Struct
-  attribute :x, Types.Instance(X).optional
+class A < Dry::Struct
+  attribute :x, Types.Instance(TopLevel1).optional
 
   def self.from_dynamic!(d)
     d = Types::Hash[d]
     new(
-      x: d["x"] ? X.from_dynamic!(d["x"]) : nil,
+      x: d["x"] ? TopLevel1.from_dynamic!(d["x"]) : nil,
     )
   end
 
@@ -198,65 +173,6 @@ class TopLevelClass < Dry::Struct
   end
 end
 
-class TopLevelElement < Dry::Struct
-  attribute :anything_array,  Types.Array(Types::Any).optional
-  attribute :bool,            Types::Bool.optional
-  attribute :double,          Types::Double.optional
-  attribute :null,            Types::Nil.optional
-  attribute :string,          Types::String.optional
-  attribute :top_level_class, TopLevelClass.optional
-
-  def self.from_dynamic!(d)
-    if schema[:anything_array].right.valid? d
-      return new(anything_array: d, bool: nil, top_level_class: nil, double: nil, null: nil, string: nil)
-    end
-    if schema[:bool].right.valid? d
-      return new(bool: d, anything_array: nil, top_level_class: nil, double: nil, null: nil, string: nil)
-    end
-    if schema[:double].right.valid? d
-      return new(double: d, anything_array: nil, bool: nil, top_level_class: nil, null: nil, string: nil)
-    end
-    if schema[:null].right.valid? d
-      return new(null: d, anything_array: nil, bool: nil, top_level_class: nil, double: nil, string: nil)
-    end
-    if schema[:string].right.valid? d
-      return new(string: d, anything_array: nil, bool: nil, top_level_class: nil, double: nil, null: nil)
-    end
-    begin
-      value = TopLevelClass.from_dynamic!(d)
-      if schema[:top_level_class].right.valid? value
-        return new(top_level_class: value, anything_array: nil, bool: nil, double: nil, null: nil, string: nil)
-      end
-    rescue
-    end
-    raise "Invalid union"
-  end
-
-  def self.from_json!(json)
-    from_dynamic!(JSON.parse(json))
-  end
-
-  def to_dynamic
-    if anything_array != nil
-      anything_array
-    elsif bool != nil
-      bool
-    elsif double != nil
-      double
-    elsif string != nil
-      string
-    elsif top_level_class != nil
-      top_level_class.to_dynamic
-    else
-      nil
-    end
-  end
-
-  def to_json(options = nil)
-    JSON.generate(to_dynamic, options)
-  end
-end
-
 class TopLevel < Dry::Struct
   attribute :anything_map, Types::Hash.meta(of: Types::Any).optional
   attribute :bool,         Types::Bool.optional
diff --git a/base/schema-ruby/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.rb b/head/schema-ruby/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.rb
index ecda6b8..9229b62 100644
--- a/base/schema-ruby/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.rb
+++ b/head/schema-ruby/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.rb
@@ -21,26 +21,26 @@ module Types
 end
 
 # (forward declaration)
-class Node < Dry::Struct; end
+class TopLevel < Dry::Struct; end
 
 class Next < Dry::Struct
-  attribute :node,   Node.optional
-  attribute :null,   Types::Nil.optional
-  attribute :string, Types::String.optional
+  attribute :null,      Types::Nil.optional
+  attribute :string,    Types::String.optional
+  attribute :top_level, TopLevel.optional
 
   def self.from_dynamic!(d)
-    begin
-      value = Node.from_dynamic!(d)
-      if schema[:node].right.valid? value
-        return new(node: value, null: nil, string: nil)
-      end
-    rescue
-    end
     if schema[:null].right.valid? d
-      return new(null: d, node: nil, string: nil)
+      return new(null: d, top_level: nil, string: nil)
     end
     if schema[:string].right.valid? d
-      return new(string: d, node: nil, null: nil)
+      return new(string: d, top_level: nil, null: nil)
+    end
+    begin
+      value = TopLevel.from_dynamic!(d)
+      if schema[:top_level].right.valid? value
+        return new(top_level: value, null: nil, string: nil)
+      end
+    rescue
     end
     raise "Invalid union"
   end
@@ -50,10 +50,10 @@ class Next < Dry::Struct
   end
 
   def to_dynamic
-    if node != nil
-      node.to_dynamic
-    elsif string != nil
+    if string != nil
       string
+    elsif top_level != nil
+      top_level.to_dynamic
     else
       nil
     end
@@ -64,34 +64,6 @@ class Next < Dry::Struct
   end
 end
 
-class Node < Dry::Struct
-  attribute :node_next, Types.Instance(Next).optional
-  attribute :value,     Types::String
-
-  def self.from_dynamic!(d)
-    d = Types::Hash[d]
-    new(
-      node_next: d["next"] ? Next.from_dynamic!(d["next"]) : nil,
-      value:     d.fetch("value"),
-    )
-  end
-
-  def self.from_json!(json)
-    from_dynamic!(JSON.parse(json))
-  end
-
-  def to_dynamic
-    {
-      "next"  => node_next&.to_dynamic,
-      "value" => value,
-    }
-  end
-
-  def to_json(options = nil)
-    JSON.generate(to_dynamic, options)
-  end
-end
-
 class TopLevel < Dry::Struct
   attribute :top_level_next, Types.Instance(Next).optional
   attribute :value,          Types::String
diff --git a/head/schema-rust/test/inputs/schema/recursive-ref-to-id.schema/default/module_under_test.rs b/head/schema-rust/test/inputs/schema/recursive-ref-to-id.schema/default/module_under_test.rs
new file mode 100644
index 0000000..649a953
--- /dev/null
+++ b/head/schema-rust/test/inputs/schema/recursive-ref-to-id.schema/default/module_under_test.rs
@@ -0,0 +1,26 @@
+// 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)]
+pub struct TopLevel {
+    pub children: Option<Vec<TopLevel>>,
+
+    pub data: Option<Data>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Data {
+    pub id: Option<String>,
+}
diff --git a/base/schema-rust/test/inputs/schema/recursive-union-flattening.schema/default/module_under_test.rs b/head/schema-rust/test/inputs/schema/recursive-union-flattening.schema/default/module_under_test.rs
index e74b744..7aebb08 100644
--- a/base/schema-rust/test/inputs/schema/recursive-union-flattening.schema/default/module_under_test.rs
+++ b/head/schema-rust/test/inputs/schema/recursive-union-flattening.schema/default/module_under_test.rs
@@ -32,8 +32,8 @@ pub enum TopLevel {
 
 #[derive(Debug, Clone, Serialize, Deserialize)]
 #[serde(untagged)]
-pub enum TopLevelElement {
-    AnythingArray(Vec<Option<serde_json::Value>>),
+pub enum PurpleTopLevel {
+    AnythingMap(HashMap<String, Option<serde_json::Value>>),
 
     Bool(bool),
 
@@ -41,43 +41,24 @@ pub enum TopLevelElement {
 
     PurpleString(String),
 
-    TopLevelClass(TopLevelClass),
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct TopLevelClass {
-    pub x: Option<X>,
+    UnionArray(Vec<Option<TopLevelElement>>),
 }
 
 #[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct XClass {
-    pub x: Option<X>,
+pub struct A {
+    pub x: Option<PurpleTopLevel>,
 }
 
 #[derive(Debug, Clone, Serialize, Deserialize)]
 #[serde(untagged)]
-pub enum XElement {
-    AnythingArray(Vec<Option<serde_json::Value>>),
-
-    Bool(bool),
-
-    Double(f64),
-
-    PurpleString(String),
-
-    XClass(XClass),
-}
+pub enum TopLevelElement {
+    A(A),
 
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(untagged)]
-pub enum X {
-    AnythingMap(HashMap<String, Option<serde_json::Value>>),
+    AnythingArray(Vec<Option<serde_json::Value>>),
 
     Bool(bool),
 
     Double(f64),
 
     PurpleString(String),
-
-    UnionArray(Vec<Option<XElement>>),
 }
diff --git a/base/schema-rust/test/inputs/schema/rust-cycle-breaker-union.schema/default/module_under_test.rs b/head/schema-rust/test/inputs/schema/rust-cycle-breaker-union.schema/default/module_under_test.rs
index 3722e3b..73329aa 100644
--- a/base/schema-rust/test/inputs/schema/rust-cycle-breaker-union.schema/default/module_under_test.rs
+++ b/head/schema-rust/test/inputs/schema/rust-cycle-breaker-union.schema/default/module_under_test.rs
@@ -14,23 +14,16 @@
 use serde::{Serialize, Deserialize};
 
 #[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct TopLevel {
-    pub next: Option<Box<Next>>,
+#[serde(untagged)]
+pub enum Next {
+    PurpleString(String),
 
-    pub value: String,
+    TopLevel(Box<TopLevel>),
 }
 
 #[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct Node {
-    pub next: Option<Box<Next>>,
+pub struct TopLevel {
+    pub next: Option<Next>,
 
     pub value: String,
 }
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(untagged)]
-pub enum Next {
-    Node(Node),
-
-    PurpleString(String),
-}
diff --git a/head/schema-scala3/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.scala b/head/schema-scala3/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.scala
new file mode 100644
index 0000000..d108d3c
--- /dev/null
+++ b/head/schema-scala3/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.scala
@@ -0,0 +1,17 @@
+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 children : Option[Seq[TopLevel]] = None,
+    val data : Option[Data] = None
+) derives Encoder.AsObject, Decoder
+
+case class Data (
+    val id : Option[String] = None
+) derives Encoder.AsObject, Decoder
diff --git a/base/schema-scala3/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.scala b/head/schema-scala3/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.scala
index 942acde..acd65d7 100644
--- a/base/schema-scala3/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.scala
+++ b/head/schema-scala3/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.scala
@@ -30,7 +30,12 @@ given Encoder[TopLevel] = Encoder.instance {
     case enc6 : NullValue => Encoder.encodeNone(enc6)
 }
 
-type TopLevelElement = Seq[Option[Json]] | Boolean | Double | Long | String | TopLevelClass | NullValue
+type PurpleTopLevel = Map[String, Option[Json]] | Boolean | Double | Long | String | Seq[TopLevelElement] | NullValue
+case class A (
+    val x : Option[PurpleTopLevel] = None
+) derives Encoder.AsObject, Decoder
+
+type TopLevelElement = A | Seq[Option[Json]] | Boolean | Double | Long | String | NullValue
 given Decoder[TopLevelElement] = {
     List[Decoder[TopLevelElement]](
         Decoder[String].widen,
@@ -38,7 +43,7 @@ given Decoder[TopLevelElement] = {
         Decoder[Long].widen,
         Decoder[Double].widen,
         Decoder[Seq[Option[Json]]].widen,
-        Decoder[TopLevelClass].widen,
+        Decoder[A].widen,
         Decoder[NullValue].widen,
     ).reduceLeft(_ or _)
 }
@@ -49,60 +54,6 @@ given Encoder[TopLevelElement] = Encoder.instance {
     case enc2 : Long => Encoder.encodeLong(enc2)
     case enc3 : Double => Encoder.encodeDouble(enc3)
     case enc4 : Seq[Option[Json]] => Encoder.encodeSeq[Option[Json]].apply(enc4)
-    case enc5 : TopLevelClass => Encoder.AsObject[TopLevelClass].apply(enc5)
-    case enc6 : NullValue => Encoder.encodeNone(enc6)
-}
-
-case class TopLevelClass (
-    val x : Option[X] = None
-) derives Encoder.AsObject, Decoder
-
-case class XClass (
-    val x : Option[X] = None
-) derives Encoder.AsObject, Decoder
-
-type XElement = Seq[Option[Json]] | Boolean | Double | Long | String | XClass | NullValue
-given Decoder[XElement] = {
-    List[Decoder[XElement]](
-        Decoder[String].widen,
-        Decoder[Boolean].widen,
-        Decoder[Long].widen,
-        Decoder[Double].widen,
-        Decoder[Seq[Option[Json]]].widen,
-        Decoder[XClass].widen,
-        Decoder[NullValue].widen,
-    ).reduceLeft(_ or _)
-}
-
-given Encoder[XElement] = Encoder.instance {
-    case enc0 : String => Encoder.encodeString(enc0)
-    case enc1 : Boolean => Encoder.encodeBoolean(enc1)
-    case enc2 : Long => Encoder.encodeLong(enc2)
-    case enc3 : Double => Encoder.encodeDouble(enc3)
-    case enc4 : Seq[Option[Json]] => Encoder.encodeSeq[Option[Json]].apply(enc4)
-    case enc5 : XClass => Encoder.AsObject[XClass].apply(enc5)
-    case enc6 : NullValue => Encoder.encodeNone(enc6)
-}
-
-type X = Map[String, Option[Json]] | Boolean | Double | Long | String | Seq[XElement] | NullValue
-given Decoder[X] = {
-    List[Decoder[X]](
-        Decoder[String].widen,
-        Decoder[Boolean].widen,
-        Decoder[Long].widen,
-        Decoder[Double].widen,
-        Decoder[Seq[XElement]].widen,
-        Decoder[Map[String, Option[Json]]].widen,
-        Decoder[NullValue].widen,
-    ).reduceLeft(_ or _)
-}
-
-given Encoder[X] = Encoder.instance {
-    case enc0 : String => Encoder.encodeString(enc0)
-    case enc1 : Boolean => Encoder.encodeBoolean(enc1)
-    case enc2 : Long => Encoder.encodeLong(enc2)
-    case enc3 : Double => Encoder.encodeDouble(enc3)
-    case enc4 : Seq[XElement] => Encoder.encodeSeq[XElement].apply(enc4)
-    case enc5 : Map[String, Option[Json]] => Encoder.encodeMap[String,Option[Json]].apply(enc5)
+    case enc5 : A => Encoder.AsObject[A].apply(enc5)
     case enc6 : NullValue => Encoder.encodeNone(enc6)
 }
diff --git a/base/schema-scala3/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.scala b/head/schema-scala3/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.scala
index 74867fc..830d2b7 100644
--- a/base/schema-scala3/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.scala
+++ b/head/schema-scala3/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.scala
@@ -7,27 +7,22 @@ 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 next : Option[Next] = None,
-    val value : String
-) derives Encoder.AsObject, Decoder
-
-case class Node (
-    val next : Option[Next] = None,
-    val value : String
-) derives Encoder.AsObject, Decoder
-
-type Next = Node | String | NullValue
+type Next = String | TopLevel | NullValue
 given Decoder[Next] = {
     List[Decoder[Next]](
         Decoder[String].widen,
-        Decoder[Node].widen,
+        Decoder[TopLevel].widen,
         Decoder[NullValue].widen,
     ).reduceLeft(_ or _)
 }
 
 given Encoder[Next] = Encoder.instance {
     case enc0 : String => Encoder.encodeString(enc0)
-    case enc1 : Node => Encoder.AsObject[Node].apply(enc1)
+    case enc1 : TopLevel => Encoder.AsObject[TopLevel].apply(enc1)
     case enc2 : NullValue => Encoder.encodeNone(enc2)
 }
+
+case class TopLevel (
+    val next : Option[Next] = None,
+    val value : String
+) derives Encoder.AsObject, Decoder
diff --git a/head/schema-scala3-upickle/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.scala b/head/schema-scala3-upickle/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.scala
new file mode 100644
index 0000000..9cd005a
--- /dev/null
+++ b/head/schema-scala3-upickle/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.scala
@@ -0,0 +1,75 @@
+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 children : Option[Seq[TopLevel]] = None,
+    val data : Option[Data] = None
+) derives OptionPickler.ReadWriter
+
+case class Data (
+    val id : Option[String] = None
+) derives OptionPickler.ReadWriter
diff --git a/base/schema-scala3-upickle/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.scala b/head/schema-scala3-upickle/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.scala
index ae94747..0c073cf 100644
--- a/base/schema-scala3-upickle/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.scala
+++ b/head/schema-scala3-upickle/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.scala
@@ -87,76 +87,29 @@ given unionWriterTopLevel: OptionPickler.Writer[TopLevel] = OptionPickler.writer
         case v: NullValue => OptionPickler.writeJs[NullValue](v)
 }
 
-type TopLevelElement = Seq[Option[ujson.Value]] | Boolean | Double | Long | String | TopLevelClass | NullValue
-given unionReaderTopLevelElement: OptionPickler.Reader[TopLevelElement] = JsonExt.badMerge[TopLevelElement](
-    JsonExt.strictString,
-    JsonExt.strictBoolean,
-    JsonExt.strictLong,
-    JsonExt.strictDouble,
-    summon[OptionPickler.Reader[Seq[Option[ujson.Value]]]],
-    summon[OptionPickler.Reader[TopLevelClass]],
-    summon[OptionPickler.Reader[NullValue]],
-    )
-
-given unionWriterTopLevelElement: OptionPickler.Writer[TopLevelElement] = OptionPickler.writer[ujson.Value].comap[TopLevelElement]{ _v =>
-    (_v: @unchecked) match 
-        case v: String => OptionPickler.writeJs[String](v)
-        case v: Boolean => OptionPickler.writeJs[Boolean](v)
-        case v: Long => OptionPickler.writeJs[Long](v)
-        case v: Double => OptionPickler.writeJs[Double](v)
-        case v: Seq[Option[ujson.Value]] => OptionPickler.writeJs[Seq[Option[ujson.Value]]](v)
-        case v: TopLevelClass => OptionPickler.writeJs[TopLevelClass](v)
-        case v: NullValue => OptionPickler.writeJs[NullValue](v)
-}
-
-case class TopLevelClass (
-    val x : Option[X] = None
-) derives OptionPickler.ReadWriter
-
-case class XClass (
-    val x : Option[X] = None
+type PurpleTopLevel = Map[String, Option[ujson.Value]] | Boolean | Double | Long | String | Seq[TopLevelElement] | NullValue
+case class A (
+    val x : Option[PurpleTopLevel] = None
 ) derives OptionPickler.ReadWriter
 
-type XElement = Seq[Option[ujson.Value]] | Boolean | Double | Long | String | XClass | NullValue
-given unionReaderXElement: OptionPickler.Reader[XElement] = JsonExt.badMerge[XElement](
+type TopLevelElement = A | Seq[Option[ujson.Value]] | Boolean | Double | Long | String | NullValue
+given unionReaderTopLevelElement: OptionPickler.Reader[TopLevelElement] = JsonExt.badMerge[TopLevelElement](
     JsonExt.strictString,
     JsonExt.strictBoolean,
     JsonExt.strictLong,
     JsonExt.strictDouble,
     summon[OptionPickler.Reader[Seq[Option[ujson.Value]]]],
-    summon[OptionPickler.Reader[XClass]],
+    summon[OptionPickler.Reader[A]],
     summon[OptionPickler.Reader[NullValue]],
     )
 
-given unionWriterXElement: OptionPickler.Writer[XElement] = OptionPickler.writer[ujson.Value].comap[XElement]{ _v =>
+given unionWriterTopLevelElement: OptionPickler.Writer[TopLevelElement] = OptionPickler.writer[ujson.Value].comap[TopLevelElement]{ _v =>
     (_v: @unchecked) match 
         case v: String => OptionPickler.writeJs[String](v)
         case v: Boolean => OptionPickler.writeJs[Boolean](v)
         case v: Long => OptionPickler.writeJs[Long](v)
         case v: Double => OptionPickler.writeJs[Double](v)
         case v: Seq[Option[ujson.Value]] => OptionPickler.writeJs[Seq[Option[ujson.Value]]](v)
-        case v: XClass => OptionPickler.writeJs[XClass](v)
-        case v: NullValue => OptionPickler.writeJs[NullValue](v)
-}
-
-type X = Map[String, Option[ujson.Value]] | Boolean | Double | Long | String | Seq[XElement] | NullValue
-given unionReaderX: OptionPickler.Reader[X] = JsonExt.badMerge[X](
-    JsonExt.strictString,
-    JsonExt.strictBoolean,
-    JsonExt.strictLong,
-    JsonExt.strictDouble,
-    summon[OptionPickler.Reader[Seq[XElement]]],
-    summon[OptionPickler.Reader[Map[String, Option[ujson.Value]]]],
-    summon[OptionPickler.Reader[NullValue]],
-    )
-
-given unionWriterX: OptionPickler.Writer[X] = OptionPickler.writer[ujson.Value].comap[X]{ _v =>
-    (_v: @unchecked) match 
-        case v: String => OptionPickler.writeJs[String](v)
-        case v: Boolean => OptionPickler.writeJs[Boolean](v)
-        case v: Long => OptionPickler.writeJs[Long](v)
-        case v: Double => OptionPickler.writeJs[Double](v)
-        case v: Seq[XElement] => OptionPickler.writeJs[Seq[XElement]](v)
-        case v: Map[String, Option[ujson.Value]] => OptionPickler.writeJs[Map[String, Option[ujson.Value]]](v)
+        case v: A => OptionPickler.writeJs[A](v)
         case v: NullValue => OptionPickler.writeJs[NullValue](v)
 }
diff --git a/base/schema-scala3-upickle/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.scala b/head/schema-scala3-upickle/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.scala
index e17ea78..5e00e79 100644
--- a/base/schema-scala3-upickle/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.scala
+++ b/head/schema-scala3-upickle/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.scala
@@ -65,26 +65,21 @@ object JsonExt:
 end JsonExt
 
 
-case class TopLevel (
-    val next : Option[Next] = None,
-    val value : String
-) derives OptionPickler.ReadWriter
-
-case class Node (
-    val next : Option[Next] = None,
-    val value : String
-) derives OptionPickler.ReadWriter
-
-type Next = Node | String | NullValue
+type Next = String | TopLevel | NullValue
 given unionReaderNext: OptionPickler.Reader[Next] = JsonExt.badMerge[Next](
     JsonExt.strictString,
-    summon[OptionPickler.Reader[Node]],
+    summon[OptionPickler.Reader[TopLevel]],
     summon[OptionPickler.Reader[NullValue]],
     )
 
 given unionWriterNext: OptionPickler.Writer[Next] = OptionPickler.writer[ujson.Value].comap[Next]{ _v =>
     (_v: @unchecked) match 
         case v: String => OptionPickler.writeJs[String](v)
-        case v: Node => OptionPickler.writeJs[Node](v)
+        case v: TopLevel => OptionPickler.writeJs[TopLevel](v)
         case v: NullValue => OptionPickler.writeJs[NullValue](v)
 }
+
+case class TopLevel (
+    val next : Option[Next] = None,
+    val value : String
+) derives OptionPickler.ReadWriter
diff --git a/head/schema-schema/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.schema b/head/schema-schema/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.schema
new file mode 100644
index 0000000..a0e11c0
--- /dev/null
+++ b/head/schema-schema/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.schema
@@ -0,0 +1,34 @@
+{
+    "$schema": "http://json-schema.org/draft-06/schema#",
+    "$ref": "#/definitions/TopLevel",
+    "definitions": {
+        "TopLevel": {
+            "type": "object",
+            "additionalProperties": {},
+            "properties": {
+                "children": {
+                    "type": "array",
+                    "items": {
+                        "$ref": "#/definitions/TopLevel"
+                    }
+                },
+                "data": {
+                    "$ref": "#/definitions/Data"
+                }
+            },
+            "required": [],
+            "title": "TopLevel"
+        },
+        "Data": {
+            "type": "object",
+            "additionalProperties": {},
+            "properties": {
+                "id": {
+                    "type": "string"
+                }
+            },
+            "required": [],
+            "title": "Data"
+        }
+    }
+}
diff --git a/base/schema-schema/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.schema b/head/schema-schema/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.schema
index 2cf8a6c..63643be 100644
--- a/base/schema-schema/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.schema
+++ b/head/schema-schema/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.schema
@@ -2,27 +2,16 @@
     "$schema": "http://json-schema.org/draft-06/schema#",
     "$ref": "#/definitions/TopLevel",
     "definitions": {
-        "TopLevelObject": {
+        "A": {
             "type": "object",
             "additionalProperties": {},
             "properties": {
                 "x": {
-                    "$ref": "#/definitions/X"
+                    "$ref": "#/definitions/PurpleTopLevel"
                 }
             },
             "required": [],
-            "title": "TopLevelObject"
-        },
-        "XObject": {
-            "type": "object",
-            "additionalProperties": {},
-            "properties": {
-                "x": {
-                    "$ref": "#/definitions/X"
-                }
-            },
-            "required": [],
-            "title": "XObject"
+            "title": "A"
         },
         "TopLevel": {
             "anyOf": [
@@ -54,11 +43,13 @@
             ],
             "title": "TopLevel"
         },
-        "TopLevelElement": {
+        "PurpleTopLevel": {
             "anyOf": [
                 {
                     "type": "array",
-                    "items": {}
+                    "items": {
+                        "$ref": "#/definitions/TopLevelElement"
+                    }
                 },
                 {
                     "type": "boolean"
@@ -67,18 +58,19 @@
                     "type": "number"
                 },
                 {
-                    "type": "null"
+                    "type": "object",
+                    "additionalProperties": {}
                 },
                 {
-                    "$ref": "#/definitions/TopLevelObject"
+                    "type": "null"
                 },
                 {
                     "type": "string"
                 }
             ],
-            "title": "TopLevelElement"
+            "title": "PurpleTopLevel"
         },
-        "XElement": {
+        "TopLevelElement": {
             "anyOf": [
                 {
                     "type": "array",
@@ -94,40 +86,13 @@
                     "type": "null"
                 },
                 {
-                    "$ref": "#/definitions/XObject"
-                },
-                {
-                    "type": "string"
-                }
-            ],
-            "title": "XElement"
-        },
-        "X": {
-            "anyOf": [
-                {
-                    "type": "array",
-                    "items": {
-                        "$ref": "#/definitions/XElement"
-                    }
-                },
-                {
-                    "type": "boolean"
-                },
-                {
-                    "type": "number"
-                },
-                {
-                    "type": "object",
-                    "additionalProperties": {}
-                },
-                {
-                    "type": "null"
+                    "$ref": "#/definitions/A"
                 },
                 {
                     "type": "string"
                 }
             ],
-            "title": "X"
+            "title": "TopLevelElement"
         }
     }
 }
diff --git a/base/schema-schema/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.schema b/head/schema-schema/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.schema
index 8696324..23a6bfd 100644
--- a/base/schema-schema/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.schema
+++ b/head/schema-schema/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.schema
@@ -18,29 +18,13 @@
             ],
             "title": "TopLevel"
         },
-        "Node": {
-            "type": "object",
-            "additionalProperties": {},
-            "properties": {
-                "next": {
-                    "$ref": "#/definitions/Next"
-                },
-                "value": {
-                    "type": "string"
-                }
-            },
-            "required": [
-                "value"
-            ],
-            "title": "Node"
-        },
         "Next": {
             "anyOf": [
                 {
                     "type": "null"
                 },
                 {
-                    "$ref": "#/definitions/Node"
+                    "$ref": "#/definitions/TopLevel"
                 },
                 {
                     "type": "string"
diff --git a/head/schema-swift/test/inputs/schema/recursive-ref-to-id.schema/default/quicktype.swift b/head/schema-swift/test/inputs/schema/recursive-ref-to-id.schema/default/quicktype.swift
new file mode 100644
index 0000000..84b7efc
--- /dev/null
+++ b/head/schema-swift/test/inputs/schema/recursive-ref-to-id.schema/default/quicktype.swift
@@ -0,0 +1,134 @@
+// 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 children: [TopLevel]?
+    let data: DataClass?
+
+    enum CodingKeys: String, CodingKey {
+        case children = "children"
+        case data = "data"
+    }
+}
+
+// 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(
+        children: [TopLevel]?? = nil,
+        data: DataClass?? = nil
+    ) -> TopLevel {
+        return TopLevel(
+            children: children ?? self.children,
+            data: data ?? self.data
+        )
+    }
+
+    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: - DataClass
+struct DataClass: Codable {
+    let id: String?
+
+    enum CodingKeys: String, CodingKey {
+        case id = "id"
+    }
+}
+
+// MARK: DataClass convenience initializers and mutators
+
+extension DataClass {
+    init(data: Data) throws {
+        self = try newJSONDecoder().decode(DataClass.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(
+        id: String?? = nil
+    ) -> DataClass {
+        return DataClass(
+            id: id ?? self.id
+        )
+    }
+
+    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/base/schema-swift/test/inputs/schema/recursive-union-flattening.schema/default/quicktype.swift b/head/schema-swift/test/inputs/schema/recursive-union-flattening.schema/default/quicktype.swift
index 3e0c38e..527a384 100644
--- a/base/schema-swift/test/inputs/schema/recursive-union-flattening.schema/default/quicktype.swift
+++ b/head/schema-swift/test/inputs/schema/recursive-union-flattening.schema/default/quicktype.swift
@@ -68,13 +68,13 @@ enum TopLevel: Codable {
     }
 }
 
-enum TopLevelElement: Codable {
-    case anythingArray([JSONAny])
+enum PurpleTopLevel: Codable {
+    case anythingMap([String: JSONAny])
     case bool(Bool)
     case double(Double)
     case integer(Int)
     case string(String)
-    case topLevelClass(TopLevelClass)
+    case unionArray([TopLevelElement])
     case null
 
     init(from decoder: Decoder) throws {
@@ -87,33 +87,33 @@ enum TopLevelElement: Codable {
             self = .integer(x)
             return
         }
-        if let x = try? container.decode([JSONAny].self) {
-            self = .anythingArray(x)
+        if let x = try? container.decode([TopLevelElement].self) {
+            self = .unionArray(x)
             return
         }
         if let x = try? container.decode(Double.self) {
             self = .double(x)
             return
         }
-        if let x = try? container.decode(String.self) {
-            self = .string(x)
+        if let x = try? container.decode([String: JSONAny].self) {
+            self = .anythingMap(x)
             return
         }
-        if let x = try? container.decode(TopLevelClass.self) {
-            self = .topLevelClass(x)
+        if let x = try? container.decode(String.self) {
+            self = .string(x)
             return
         }
         if container.decodeNil() {
             self = .null
             return
         }
-        throw DecodingError.typeMismatch(TopLevelElement.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for TopLevelElement"))
+        throw DecodingError.typeMismatch(PurpleTopLevel.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for PurpleTopLevel"))
     }
 
     func encode(to encoder: Encoder) throws {
         var container = encoder.singleValueContainer()
         switch self {
-        case .anythingArray(let x):
+        case .anythingMap(let x):
             try container.encode(x)
         case .bool(let x):
             try container.encode(x)
@@ -123,7 +123,7 @@ enum TopLevelElement: Codable {
             try container.encode(x)
         case .string(let x):
             try container.encode(x)
-        case .topLevelClass(let x):
+        case .unionArray(let x):
             try container.encode(x)
         case .null:
             try container.encodeNil()
@@ -131,64 +131,20 @@ enum TopLevelElement: Codable {
     }
 }
 
-// MARK: - TopLevelClass
-struct TopLevelClass: Codable {
-    let x: X?
-
-    enum CodingKeys: String, CodingKey {
-        case x = "x"
-    }
-}
-
-// MARK: TopLevelClass convenience initializers and mutators
-
-extension TopLevelClass {
-    init(data: Data) throws {
-        self = try newJSONDecoder().decode(TopLevelClass.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(
-        x: X?? = nil
-    ) -> TopLevelClass {
-        return TopLevelClass(
-            x: x ?? self.x
-        )
-    }
-
-    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: - XClass
-struct XClass: Codable {
-    let x: X?
+// MARK: - A
+struct A: Codable {
+    let x: PurpleTopLevel?
 
     enum CodingKeys: String, CodingKey {
         case x = "x"
     }
 }
 
-// MARK: XClass convenience initializers and mutators
+// MARK: A convenience initializers and mutators
 
-extension XClass {
+extension A {
     init(data: Data) throws {
-        self = try newJSONDecoder().decode(XClass.self, from: data)
+        self = try newJSONDecoder().decode(A.self, from: data)
     }
 
     init(_ json: String, using encoding: String.Encoding = .utf8) throws {
@@ -203,9 +159,9 @@ extension XClass {
     }
 
     func with(
-        x: X?? = nil
-    ) -> XClass {
-        return XClass(
+        x: PurpleTopLevel?? = nil
+    ) -> A {
+        return A(
             x: x ?? self.x
         )
     }
@@ -219,13 +175,13 @@ extension XClass {
     }
 }
 
-enum XElement: Codable {
+enum TopLevelElement: Codable {
+    case a(A)
     case anythingArray([JSONAny])
     case bool(Bool)
     case double(Double)
     case integer(Int)
     case string(String)
-    case xClass(XClass)
     case null
 
     init(from decoder: Decoder) throws {
@@ -250,84 +206,23 @@ enum XElement: Codable {
             self = .string(x)
             return
         }
-        if let x = try? container.decode(XClass.self) {
-            self = .xClass(x)
+        if let x = try? container.decode(A.self) {
+            self = .a(x)
             return
         }
         if container.decodeNil() {
             self = .null
             return
         }
-        throw DecodingError.typeMismatch(XElement.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for XElement"))
+        throw DecodingError.typeMismatch(TopLevelElement.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for TopLevelElement"))
     }
 
     func encode(to encoder: Encoder) throws {
         var container = encoder.singleValueContainer()
         switch self {
-        case .anythingArray(let x):
-            try container.encode(x)
-        case .bool(let x):
+        case .a(let x):
             try container.encode(x)
-        case .double(let x):
-            try container.encode(x)
-        case .integer(let x):
-            try container.encode(x)
-        case .string(let x):
-            try container.encode(x)
-        case .xClass(let x):
-            try container.encode(x)
-        case .null:
-            try container.encodeNil()
-        }
-    }
-}
-
-enum X: Codable {
-    case anythingMap([String: JSONAny])
-    case bool(Bool)
-    case double(Double)
-    case integer(Int)
-    case string(String)
-    case unionArray([XElement])
-    case null
-
-    init(from decoder: Decoder) throws {
-        let container = try decoder.singleValueContainer()
-        if let x = try? container.decode(Bool.self) {
-            self = .bool(x)
-            return
-        }
-        if let x = try? container.decode(Int.self) {
-            self = .integer(x)
-            return
-        }
-        if let x = try? container.decode([XElement].self) {
-            self = .unionArray(x)
-            return
-        }
-        if let x = try? container.decode(Double.self) {
-            self = .double(x)
-            return
-        }
-        if let x = try? container.decode([String: JSONAny].self) {
-            self = .anythingMap(x)
-            return
-        }
-        if let x = try? container.decode(String.self) {
-            self = .string(x)
-            return
-        }
-        if container.decodeNil() {
-            self = .null
-            return
-        }
-        throw DecodingError.typeMismatch(X.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for X"))
-    }
-
-    func encode(to encoder: Encoder) throws {
-        var container = encoder.singleValueContainer()
-        switch self {
-        case .anythingMap(let x):
+        case .anythingArray(let x):
             try container.encode(x)
         case .bool(let x):
             try container.encode(x)
@@ -337,8 +232,6 @@ enum X: Codable {
             try container.encode(x)
         case .string(let x):
             try container.encode(x)
-        case .unionArray(let x):
-            try container.encode(x)
         case .null:
             try container.encodeNil()
         }
diff --git a/base/schema-swift/test/inputs/schema/rust-cycle-breaker-union.schema/default/quicktype.swift b/head/schema-swift/test/inputs/schema/rust-cycle-breaker-union.schema/default/quicktype.swift
index 94813e3..25ec53c 100644
--- a/base/schema-swift/test/inputs/schema/rust-cycle-breaker-union.schema/default/quicktype.swift
+++ b/head/schema-swift/test/inputs/schema/rust-cycle-breaker-union.schema/default/quicktype.swift
@@ -5,56 +5,43 @@
 
 import Foundation
 
-// MARK: - TopLevel
-struct TopLevel: Codable {
-    let next: Next?
-    let value: String
-
-    enum CodingKeys: String, CodingKey {
-        case next = "next"
-        case value = "value"
-    }
-}
-
-// MARK: TopLevel convenience initializers and mutators
-
-extension TopLevel {
-    init(data: Data) throws {
-        self = try newJSONDecoder().decode(TopLevel.self, from: data)
-    }
+enum Next: Codable {
+    case string(String)
+    case topLevel(TopLevel)
+    case null
 
-    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)
+    init(from decoder: Decoder) throws {
+        let container = try decoder.singleValueContainer()
+        if let x = try? container.decode(String.self) {
+            self = .string(x)
+            return
         }
-        try self.init(data: data)
-    }
-
-    init(fromURL url: URL) throws {
-        try self.init(data: try Data(contentsOf: url))
-    }
-
-    func with(
-        next: Next?? = nil,
-        value: String? = nil
-    ) -> TopLevel {
-        return TopLevel(
-            next: next ?? self.next,
-            value: value ?? self.value
-        )
-    }
-
-    func jsonData() throws -> Data {
-        return try newJSONEncoder().encode(self)
+        if let x = try? container.decode(TopLevel.self) {
+            self = .topLevel(x)
+            return
+        }
+        if container.decodeNil() {
+            self = .null
+            return
+        }
+        throw DecodingError.typeMismatch(Next.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for Next"))
     }
 
-    func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
-        return String(data: try self.jsonData(), encoding: encoding)
+    func encode(to encoder: Encoder) throws {
+        var container = encoder.singleValueContainer()
+        switch self {
+        case .string(let x):
+            try container.encode(x)
+        case .topLevel(let x):
+            try container.encode(x)
+        case .null:
+            try container.encodeNil()
+        }
     }
 }
 
-// MARK: - Node
-struct Node: Codable {
+// MARK: - TopLevel
+class TopLevel: Codable {
     let next: Next?
     let value: String
 
@@ -62,31 +49,37 @@ struct Node: Codable {
         case next = "next"
         case value = "value"
     }
+
+    init(next: Next?, value: String) {
+        self.next = next
+        self.value = value
+    }
 }
 
-// MARK: Node convenience initializers and mutators
+// MARK: TopLevel convenience initializers and mutators
 
-extension Node {
-    init(data: Data) throws {
-        self = try newJSONDecoder().decode(Node.self, from: data)
+extension TopLevel {
+    convenience init(data: Data) throws {
+        let me = try newJSONDecoder().decode(TopLevel.self, from: data)
+        self.init(next: me.next, value: me.value)
     }
 
-    init(_ json: String, using encoding: String.Encoding = .utf8) throws {
+    convenience 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 {
+    convenience init(fromURL url: URL) throws {
         try self.init(data: try Data(contentsOf: url))
     }
 
     func with(
         next: Next?? = nil,
         value: String? = nil
-    ) -> Node {
-        return Node(
+    ) -> TopLevel {
+        return TopLevel(
             next: next ?? self.next,
             value: value ?? self.value
         )
@@ -101,41 +94,6 @@ extension Node {
     }
 }
 
-indirect enum Next: Codable {
-    case node(Node)
-    case string(String)
-    case null
-
-    init(from decoder: Decoder) throws {
-        let container = try decoder.singleValueContainer()
-        if let x = try? container.decode(String.self) {
-            self = .string(x)
-            return
-        }
-        if let x = try? container.decode(Node.self) {
-            self = .node(x)
-            return
-        }
-        if container.decodeNil() {
-            self = .null
-            return
-        }
-        throw DecodingError.typeMismatch(Next.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for Next"))
-    }
-
-    func encode(to encoder: Encoder) throws {
-        var container = encoder.singleValueContainer()
-        switch self {
-        case .node(let x):
-            try container.encode(x)
-        case .string(let x):
-            try container.encode(x)
-        case .null:
-            try container.encodeNil()
-        }
-    }
-}
-
 // MARK: - Helper functions for creating encoders and decoders
 
 func newJSONDecoder() -> JSONDecoder {
diff --git a/head/schema-typescript/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.ts b/head/schema-typescript/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.ts
new file mode 100644
index 0000000..bb981e5
--- /dev/null
+++ b/head/schema-typescript/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.ts
@@ -0,0 +1,194 @@
+// 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 {
+    children?: TopLevel[];
+    data?:     Data;
+    [property: string]: unknown;
+}
+
+export interface Data {
+    id?: string;
+    [property: string]: unknown;
+}
+
+// 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: "children", js: "children", typ: u(undefined, a(r("TopLevel"))) },
+        { json: "data", js: "data", typ: u(undefined, r("Data")) },
+    ], "any"),
+    "Data": o([
+        { json: "id", js: "id", typ: u(undefined, "") },
+    ], "any"),
+};
diff --git a/base/schema-typescript/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.ts b/head/schema-typescript/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.ts
index d881b39..131f351 100644
--- a/base/schema-typescript/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.ts
+++ b/head/schema-typescript/test/inputs/schema/recursive-union-flattening.schema/default/TopLevel.ts
@@ -9,31 +9,24 @@
 
 export type TopLevel = TopLevelElement[] | boolean | number | number | { [key: string]: unknown } | null | string;
 
-export type TopLevelElement = unknown[] | boolean | number | null | TopLevelObject | string;
+export type PurpleTopLevel = TopLevelElement[] | boolean | number | { [key: string]: unknown } | null | string;
 
-export interface TopLevelObject {
-    x?: X;
+export interface A {
+    x?: PurpleTopLevel;
     [property: string]: unknown;
 }
 
-export interface XObject {
-    x?: X;
-    [property: string]: unknown;
-}
-
-export type XElement = unknown[] | boolean | number | null | XObject | string;
-
-export type X = XElement[] | boolean | number | { [key: string]: unknown } | null | string;
+export type TopLevelElement = unknown[] | boolean | number | null | A | string;
 
 // 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), u(a(u(a("any"), true, 3.14, null, r("TopLevelObject"), "")), true, 3.14, 0, m("any"), null, ""));
+        return cast(JSON.parse(json), u(a(u(a("any"), true, 3.14, null, r("A"), "")), true, 3.14, 0, m("any"), null, ""));
     }
 
     public static topLevelToJson(value: TopLevel): string {
-        return JSON.stringify(uncast(value, u(a(u(a("any"), true, 3.14, null, r("TopLevelObject"), "")), true, 3.14, 0, m("any"), null, "")), null, 2);
+        return JSON.stringify(uncast(value, u(a(u(a("any"), true, 3.14, null, r("A"), "")), true, 3.14, 0, m("any"), null, "")), null, 2);
     }
 }
 
@@ -191,10 +184,7 @@ function r(name: string) {
 }
 
 const typeMap: any = {
-    "TopLevelObject": o([
-        { json: "x", js: "x", typ: u(undefined, u(a(u(a("any"), true, 3.14, null, r("XObject"), "")), true, 3.14, m("any"), null, "")) },
-    ], "any"),
-    "XObject": o([
-        { json: "x", js: "x", typ: u(undefined, u(a(u(a("any"), true, 3.14, null, r("XObject"), "")), true, 3.14, m("any"), null, "")) },
+    "A": o([
+        { json: "x", js: "x", typ: u(undefined, u(a(u(a("any"), true, 3.14, null, r("A"), "")), true, 3.14, m("any"), null, "")) },
     ], "any"),
 };
diff --git a/base/schema-typescript/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.ts b/head/schema-typescript/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.ts
index a88afa4..64e1e43 100644
--- a/base/schema-typescript/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.ts
+++ b/head/schema-typescript/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.ts
@@ -7,20 +7,14 @@
 // These functions will throw an error if the JSON doesn't
 // match the expected interface, even if the JSON is valid.
 
-export interface TopLevel {
-    next?: Next;
-    value: string;
-    [property: string]: unknown;
-}
+export type Next = null | TopLevel | string;
 
-export interface Node {
+export interface TopLevel {
     next?: Next;
     value: string;
     [property: string]: unknown;
 }
 
-export type Next = null | Node | string;
-
 // Converts JSON strings to/from your types
 // and asserts the results of JSON.parse at runtime
 export class Convert {
@@ -188,11 +182,7 @@ function r(name: string) {
 
 const typeMap: any = {
     "TopLevel": o([
-        { json: "next", js: "next", typ: u(undefined, u(null, r("Node"), "")) },
-        { json: "value", js: "value", typ: "" },
-    ], "any"),
-    "Node": o([
-        { json: "next", js: "next", typ: u(undefined, u(null, r("Node"), "")) },
+        { json: "next", js: "next", typ: u(undefined, u(null, r("TopLevel"), "")) },
         { json: "value", js: "value", typ: "" },
     ], "any"),
 };
diff --git a/head/schema-typescript-zod/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.ts b/head/schema-typescript-zod/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.ts
new file mode 100644
index 0000000..39e4d6a
--- /dev/null
+++ b/head/schema-typescript-zod/test/inputs/schema/recursive-ref-to-id.schema/default/TopLevel.ts
@@ -0,0 +1,18 @@
+import * as z from "zod";
+
+
+export type TopLevel = {
+    "children"?: Array<TopLevel>;
+    "data"?: Data;
+};
+export const TopLevelSchema: z.ZodType<TopLevel> = z.lazy(() =>
+    z.object({
+        "children": z.array(TopLevelSchema).optional(),
+        "data": DataSchema.optional(),
+    })
+);
+
+export const DataSchema = z.object({
+    "id": z.string().optional(),
+});
+export type Data = z.infer<typeof DataSchema>;
diff --git a/base/schema-typescript-zod/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.ts b/head/schema-typescript-zod/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.ts
index 9036c1e..f5a2993 100644
--- a/base/schema-typescript-zod/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.ts
+++ b/head/schema-typescript-zod/test/inputs/schema/rust-cycle-breaker-union.schema/default/TopLevel.ts
@@ -1,19 +1,13 @@
 import * as z from "zod";
 
 
-export type Node = {
-    "next"?: Node | null | string;
+export type TopLevel = {
+    "next"?: TopLevel | null | string;
     "value": string;
 };
-export const NodeSchema: z.ZodType<Node> = z.lazy(() =>
+export const TopLevelSchema: z.ZodType<TopLevel> = z.lazy(() =>
     z.object({
-        "next": z.union([z.null(), NodeSchema, z.string()]).optional(),
+        "next": z.union([z.null(), TopLevelSchema, z.string()]).optional(),
         "value": z.string(),
     })
 );
-
-export const TopLevelSchema = z.object({
-    "next": z.union([z.null(), NodeSchema, z.string()]).optional(),
-    "value": z.string(),
-});
-export type TopLevel = z.infer<typeof TopLevelSchema>;
