<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[quicktype]]></title><description><![CDATA[Generate types and converters from JSON, Schema, and GraphQL.]]></description><link>https://blog.quicktype.io/</link><image><url>http://blog.quicktype.io/favicon.png</url><title>quicktype</title><link>https://blog.quicktype.io/</link></image><generator>Ghost 1.19</generator><lastBuildDate>Tue, 14 Jan 2020 11:56:44 GMT</lastBuildDate><atom:link href="https://blog.quicktype.io/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Transformed String Types: How quicktype Converts JSON String Values to Stronger Types]]></title><description><![CDATA[JSON often string-encodes complex data types, such as date-times. When coding, we would like to use our programming language’s native types, not strings. quicktype lets us do that. In this blog post, I'll show how straightforward it was to add two new transformed string types: UUIDs and booleans.]]></description><link>https://blog.quicktype.io/transformed-string-types/</link><guid isPermaLink="false">5b720dd620ac8006ddecccbc</guid><category><![CDATA[how-to]]></category><category><![CDATA[internals]]></category><dc:creator><![CDATA[Mark]]></dc:creator><pubDate>Mon, 20 Aug 2018 14:18:46 GMT</pubDate><content:encoded><![CDATA[<div class="kg-card-markdown"><p>JSON has a limited selection of data types; more complex types, such as dates, are often represented as strings. When writing code, we would prefer to use our programming language’s stronger, more expressive types (e.g. <code>DateTimeOffset</code> in C#) rather than strings.</p>
<p>For example, given the JSON:</p>
<pre><code class="language-json">{
    &quot;name&quot;: &quot;David&quot;,
    &quot;favoriteDate&quot;: &quot;2012-04-23T18:25:43.511Z&quot;
}
</code></pre>
<br>
<p>quicktype generates this type and corresponding marshaling code in C#:</p>
<pre><code class="language-csharp">public partial class Person
{
    [JsonProperty(&quot;name&quot;)]
    public string Name { get; set; }

    [JsonProperty(&quot;favoriteDate&quot;)]
    public DateTimeOffset FavoriteDate { get; set; }
}
</code></pre>
<br>
<p>This allows the programmer to write safer, more expressive code:</p>
<pre><code class="language-csharp">const person = Person.FromJson(jsonString);
// This comparison would not compile if FavoriteDate were string:
if (person.FavoriteDate &lt; DateTimeOffset.Now)
{
    Console.WriteLine($&quot;{person.Name} is nostalgic&quot;);
}
</code></pre>
<br>
<p>Many JSON APIs even string-encode values for which JSON types exists, such as booleans: <code>{ “goodIdea”: “false” }</code>. Here, too, we would rather use booleans and rely on JSON de/serialization to do the conversion for us transparently.</p>
<p>In this post, I'll show how we added two new transformed string types (TSTs) to C# and Python: UUIDs and booleans. With this, you can take your <a href="https://blog.quicktype.io/customizing-quicktype/">customization of quicktype</a> a step further, and maybe contribute a PR or two!</p>
<h4 id="thefeature">The feature</h4>
<p>You've probably seen JSON that looks like this:</p>
<pre><code class="language-json">{
    &quot;name&quot;: &quot;Mark&quot;,
    &quot;weight&quot;: &quot;215&quot;,
    &quot;can-juggle&quot;: &quot;true&quot;,
    &quot;id&quot;: &quot;8352a2a8-b0cb-4cb6-8484-357cbcb6d5aa&quot;
}
</code></pre>
<br>
<p>Using strings for numbers and booleans isn’t ideal because there is more potential for error. JSON frameworks will treat them as regular strings, which means you have to write the code to do the conversion back and forth. If you <a href="https://app.quicktype.io?share=dzGz9LILjk1G6Sf2WHOP">ask quicktype</a> to infer the type for the above data, however, it'll give you this C# class:</p>
<pre><code class="language-csharp">public partial class Person
{
   public string Name { get; set; }
   public long Weight { get; set; }
   public bool CanJuggle { get; set; }
   public Guid Id { get; set; }
}
</code></pre>
<br>
<p>Now it’s easy to manipulate those values directly, and if you let quicktype <a href="https://app.quicktype.io?share=yaBo7XjrY7Ktwyi7pz9s">generate de/serializers</a> as well, convert from and to JSON:</p>
<pre><code class="language-csharp">var person = Person.FromJson(jsonString);
person.Weight -= 5;
jsonString = person.ToJson();
</code></pre>
<br>
<p>Let's see how we implemented booleans and UUIDs!</p>
<h4 id="addingbooleans">Adding booleans</h4>
<p>The code for these two TSTs (transformed string types) is split up into three commits each. In <a href="https://github.com/quicktype/quicktype/commit/dcd2b2657a114cec5d5adbdd134e37b2c2678afd">the first commit for booleans</a>, we tell quicktype about stringified booleans and how they are represented as strings in JSON.</p>
<p>Teaching quicktype about the new TST is one line of code in <code>Type.ts</code>, adding a property to <code>transformedStringTypeTargetTypeKinds</code>:</p>
<pre><code class="language-javascript">&quot;bool-string&quot;: { jsonSchema: &quot;boolean&quot;, primitive: &quot;bool&quot; } as TransformedStringTypeTargets
</code></pre>
<br>
<p>What it says is that we want a new TST called <code>bool-string</code>, which has the JSON Schema “format” <code>boolean</code>, and which corresponds to quicktype's <a href="https://github.com/quicktype/quicktype/blob/970ab10ed85a219473dbcb9d5daa3e5f3843c90e/src/quicktype-core/Type.ts#L65">primitive type</a> <code>bool</code>.</p>
<p>To detect stringified booleans in input JSON we modify the function <code>inferTransformedStringTypeKindForString</code> in <code>StringTypes.ts</code>:</p>
<pre><code class="language-javascript">/**
 * JSON inference calls this function to figure out whether a given string is to be
 * transformed into a higher level type.  Must return undefined if not, otherwise the
 * type kind of the transformed string type.
 *
 * @param s The string for which to determine the transformed string type kind.
 */
export function inferTransformedStringTypeKindForString(s: string): TransformedStringTypeKind | undefined {
    if (s.length === 0 || &quot;0123456789-abcdeft&quot;.indexOf(s[0]) &lt; 0) return undefined;

    if (isDate(s)) {
        return &quot;date&quot;;
    } else if (isTime(s)) {
        return &quot;time&quot;;
    } else if (isDateTime(s)) {
        return &quot;date-time&quot;;
    } else if (isIntegerString(s)) {
        return &quot;integer-string&quot;;
    } else if (s === &quot;false&quot; || s === &quot;true&quot;) {
        return &quot;bool-string&quot;;
    } else if (isUUID(s)) {
        return &quot;uuid&quot;;
    }
    return undefined;
}
</code></pre>
<br>
<p>These two new lines do the actual business:</p>
<pre><code class="language-javascript">} else if (s === &quot;false&quot; || s === &quot;true&quot;) {
   return &quot;bool-string&quot;;
</code></pre>
<br>
<p>The first line of the function is an optimization: If the string is empty, or it doesn't start with one of the characters in that list then it can't be one of the string types we detect, so we bail out early. All we have to do for booleans is to add the letters <code>f</code> and <code>t</code>. If we wanted to also interpret the strings <code>&quot;no&quot;</code> and <code>&quot;yes&quot;</code> as booleans, we'd have to add the letters <code>n</code> and <code>y</code>, too.</p>
<p>At this point, if we <a href="https://app.quicktype.io?share=G73KaAmswq4y5iFUmO29">ask quicktype to produce a JSON Schema</a> for this JSON:</p>
<pre><code class="language-json">{
    &quot;foo&quot;: &quot;true&quot;
}
</code></pre>
<br>
<p>we get this:</p>
<pre><code class="language-json">{
    &quot;$schema&quot;: &quot;http://json-schema.org/draft-06/schema#&quot;,
    &quot;$ref&quot;: &quot;#/definitions/TopLevel&quot;,
    &quot;definitions&quot;: {
        &quot;TopLevel&quot;: {
            &quot;type&quot;: &quot;object&quot;,
            &quot;additionalProperties&quot;: false,
            &quot;properties&quot;: {
                &quot;foo&quot;: {
                    &quot;type&quot;: &quot;string&quot;,
                    &quot;format&quot;: &quot;boolean&quot;
                }
            },
            &quot;required&quot;: [&quot;foo&quot;],
            &quot;title&quot;: &quot;TopLevel&quot;
        }
    }
}
</code></pre>
<br>
<p>Notice how the <code>type</code> for <code>foo</code> is <code>string</code>, with <code>boolean</code> as its <code>format</code>. That's what we specified as the <code>jsonSchema</code> property in the first part of the commit. <code>format</code> is an &quot;assertion&quot; that’s part of <a href="https://datatracker.ietf.org/doc/draft-handrews-json-schema-validation/?include_text=1">JSON Schema</a> which allows string types to be constrained. An example for a <code>format</code> that’s part of the JSON Schema specification is <code>”date-time”</code> for date-time strings. <code>boolean</code> isn’t in the spec, but we’re allowed to invent our own. Unfortunately, the JSON Schema verifier <a href="https://www.npmjs.com/package/ajv">Ajv</a> that we use in our test suite fails if it sees this new unknown <code>format</code>, which is why the last part of the commit tells Ajv to ignore it:</p>
<pre><code class="language-javascript">let ajv = new Ajv({ format: &quot;full&quot;, unknownFormats: [&quot;integer&quot;, &quot;boolean&quot;] });
</code></pre>
<br>
<h5 id="c">C#</h5>
<p>The <a href="https://github.com/quicktype/quicktype/commit/9493484bb998c8565926c052fde0ae5a038421cc">commit that adds support for stringified booleans to C#</a> starts out by adding a case to the function <code>needTransformerForType</code>:</p>
<pre><code class="language-javascript">if (t.kind === &quot;integer-string&quot; || t.kind === &quot;bool-string&quot;) return &quot;manual&quot;;
</code></pre>
<br>
<p><code>manual</code> here means that when the renderer emits the C# code for a <code>bool-string</code> property, it adds a <a href="https://www.newtonsoft.com/json/help/html/JsonConverterAttributeClass.htm"><code>JsonConverterAttribute</code></a> to the property that specifies a <a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonConverter.htm"><code>JsonConverter</code></a> to convert said property. Since only some booleans are decoded from strings, this explicit attribute is required. Here is the code for one real boolean, and one converted from strings:</p>
<pre><code class="language-csharp">[JsonProperty(&quot;real-bool&quot;)]
public bool RealBool { get; set; }

[JsonProperty(&quot;string-bool&quot;)]
[JsonConverter(typeof(ParseStringConverter))]
public bool StringBool { get; set; }
</code></pre>
<br>
<p>The next part adds a line to <code>stringTypeMapping</code>:</p>
<pre><code class="language-javascript">mapping.set(&quot;bool-string&quot;, &quot;bool-string&quot;);
</code></pre>
<br>
<p>All entries not explicitly set in <code>mapping</code> are treated as if they were set to <code>string</code>, which means that without this line, quicktype would make each <code>bool-string</code> in the input into a <code>string</code> for C#. You would get correct code, but stringified booleans would still just be handled like plain strings. You might think that <code>mapping</code> should just be a set of all types which are to be kept as-is, but sometimes types are mapped to other non-string types:</p>
<pre><code class="language-javascript">mapping.set(&quot;date&quot;, &quot;date-time&quot;);
mapping.set(&quot;time&quot;, &quot;date-time&quot;);
mapping.set(&quot;date-time&quot;, &quot;date-time&quot;);
</code></pre>
<br>
<p>Dates, times, and date-times are all mapped to the same type <code>date-time</code>, which in C# is represented by <code>DateTimeOffset</code>. That's because C# doesn't have specialized types for dates and times, only a combined date-time type.</p>
<p>The last two pieces are about how to do the actual conversions between strings and booleans when your JSON is de/serialized at runtime. The code generators for the conversions are cases for the type <code>bool</code> in the transformers <code>ParseStringTransformer</code> and <code>StringifyTransformer</code>. C# does not have a type that corresponds to <code>bool-string</code>; it only has <code>bool</code> and <code>string</code>. Transformers are the pieces that convert between <code>bool</code> and <code>string</code>, and the <code>CSharpRenderer</code> has to generate the code for them. Here's the case for <code>ParseStringTransformer</code>:</p>
<pre><code class="language-javascript">case &quot;bool&quot;:
   this.emitLine(&quot;bool b;&quot;);
   this.emitLine(&quot;if (Boolean.TryParse(&quot;, variable, &quot;, out b))&quot;);
   this.emitBlock(() =&gt; this.emitConsume(&quot;b&quot;, xfer.consumer, targetType, emitFinish));
   break;
</code></pre>
<br>
<p>Here’s code that it generates:</p>
<pre><code class="language-csharp">bool b;
if (Boolean.TryParse(value, out b))
{
   return b;
}
</code></pre>
<br>
<p><code>variable</code> is where the string to be converted is stored. <code>emitBlock</code> produces the curly-braces block, the insides of which are generated by <code>emitConsume</code>. <code>xfer.consumer</code> is an optional transformer for the result (the variable <code>b</code>) of this conversion. In this example, we don't have a consumer, but we'll see one later on. <code>targetType</code> is the type that is produced at the end of this transformer chain, i.e., once the consumer, and its consumer, and its consumer's consumer, etc., are done. It just has to be passed through. <code>emitFinish</code> emits the code for what needs to happen at that end of the transformer chain, which is the <code>return</code> statement in this example. There might be other transformers to try after this one, which is why if <code>TryParse</code> fails, the generated code just continues on. On the other hand, if this is the last hope of decoding this string, the code to throw an exception is generated automatically by the <code>CSharpRenderer</code>.</p>
<p>On to the last part of this commit to support stringified booleans in C#: the case for <code>StringifyTransformer</code>, which turns boolean values back into JSON string values! It looks similar to the switch case for <code>ParseStringTransformer</code>:</p>
<pre><code class="language-javascript">case &quot;bool&quot;:
   this.emitLine(&quot;var boolString = &quot;, variable, ' ? &quot;true&quot; : &quot;false&quot;;');
   return this.emitConsume(&quot;boolString&quot;, xfer.consumer, targetType, emitFinish);
</code></pre>
<br>
<p>The first line does a switch on the boolean to get its string value, and the second line is almost identical to what we've seen before. The relevant difference is that the code returns the result of <code>emitConsume</code>. I mentioned above that the <code>CSharpRenderer</code> generates code for the case when the runtime transformation fails. This code is only generated, however, if the transformation <em>can</em> actually fail. How does the renderer know? The function we modified returns <code>true</code> if the transformation is guaranteed to succeed, i.e., never falls through. By default it returns <code>false</code>, signifying the transformation can fail, which is why we only had to <code>break</code> for the <code>ParseStringTransformer</code>. Here, we know that our part of the transformer chain always succeeds: a boolean can only be either <code>false</code> or <code>true</code>, and we handle both cases. However, the consumer might still fail, so we return the failability result of <code>emitConsume</code>.</p>
<p>That's all that's needed to make stringified booleans work in C#.</p>
<h5 id="python">Python</h5>
<p>Now let me explain how I implemented <a href="https://github.com/quicktype/quicktype/commit/5acd550355b143c736b0fbb646589c40ee8a9ef1">stringified boolean support in Python</a>. The first part, which we've already seen above, lets quicktype know that <code>PythonRenderer</code> supports stringified booleans:</p>
<pre><code class="language-javascript">mapping.set(&quot;bool-string&quot;, &quot;bool-string&quot;);
</code></pre>
<br>
<p>The next bit, in <code>needsTransformerForType</code>, is easier to explain than the C# version. In C# we have help from the Json.NET framework, which has lots of converters built in, but in Python our generated code has to do it all on its own, so it doesn’t distinguish between “manual” and “automatic” conversion. That’s why, for <code>bool-string</code>, we always return <code>true</code>:</p>
<pre><code class="language-javascript">return t.kind === &quot;integer-string&quot; || t.kind === &quot;bool-string&quot;;
</code></pre>
<br>
<p>In Python, if we can express a transformer as a simple, short expression, we emit it inline; otherwise, we emit a function for it. As we'll see below, converting a boolean into a string is indeed a short expression, but the reverse is not, so we need a function. We only want to emit this function when we actually have stringified booleans in our JSON, which is why the <code>PythonRenderer</code> keeps track of which converter functions it has to emit. First, we have to add a new case to the type of all converter functions, <code>ConverterFunction</code>:</p>
<pre><code class="language-javascript">| &quot;from-stringified-bool&quot;
</code></pre>
<br>
<p>Next is the code that emits the converter function:</p>
<pre><code class="language-javascript">protected emitFromStringifiedBoolConverter(): void {
   this.emitBlock(
       [&quot;def from_stringified_bool(x&quot;, this.typeHint(&quot;: str&quot;), &quot;)&quot;, this.typeHint(&quot; -&gt; bool&quot;), &quot;:&quot;],
       () =&gt; {
           this.emitBlock('if x == &quot;true&quot;:', () =&gt; this.emitLine(&quot;return True&quot;));
           this.emitBlock('if x == &quot;false&quot;:', () =&gt; this.emitLine(&quot;return False&quot;));
           this.emitLine(&quot;assert False&quot;);
       }
   );
}
</code></pre>
<br>
<p>The calls to <code>typeHint</code> make sure that the type hints are only emitted when the user selects a Python version that supports types. Note another difference to C#: If the conversion fails, an exception is thrown.</p>
<p>The function <code>emitConverter</code> has a case for each converter function that just calls its emitter:</p>
<pre><code class="language-javascript">case &quot;from-stringified-bool&quot;:
   return this.emitFromStringifiedBoolConverter();
</code></pre>
<br>
<p>Next up is producing code for the <code>bool</code> case of <code>ParseStringTransformer</code>:</p>
<pre><code class="language-javascript">case &quot;bool&quot;:
   vol = this.convFn(&quot;from-stringified-bool&quot;, inputTransformer);
   break;
</code></pre>
<br>
<p><code>convFn</code> emits a call to the function <code>from_stringified_bool</code>, and its argument is the result of the transformation <code>inputTransformer</code>: in Python we go the other way around to emitting a transformer chain: The consumers are generated first, with the producers (the transformers that preceded them) nested inside.</p>
<p>The case for <code>StringifyTransformer</code> doesn't have to produce a function call since we can do the conversion as a simple, inline expression:</p>
<pre><code class="language-javascript">case &quot;bool&quot;:
   vol = compose(inputTransformer, v =&gt; [&quot;str(&quot;, v, &quot;).lower()&quot;]);
   break;
</code></pre>
<br>
<p>The <code>compose</code> function emits code for the <code>inputTransformer</code> and then passes the result on to the expression that the arrow function emits. Here’s the line of code that’s generated for converting the boolean property <code>foo</code> to a string:</p>
<pre><code class="language-python">result[&quot;foo&quot;] = from_str(str(self.foo).lower())
</code></pre>
<br>
<p>That's it for Python!</p>
<h4 id="addinguuids">Adding UUIDs</h4>
<p><a href="https://en.wikipedia.org/wiki/Universally_unique_identifier">UUIDs (universally unique identifiers)</a> are strings that are commonly used to identify items, such as in primary keys for rows in a database table, or data items in REST APIs, and as such are often found in JSON data.</p>
<p>After having seen the code for booleans, most of the code for UUIDs doesn't hold any surprises, but there are still a few details that are different. Let's start at <a href="https://github.com/quicktype/quicktype/commit/61cc926758352090ccfbfec425a9585a0ebb1555">the first commit</a>, which adds the <code>uuid</code> type. The main point of interest here is its entry in <code>transformedStringTypeTargetTypeKinds</code>:</p>
<pre><code class="language-javascript">uuid: { jsonSchema: &quot;uuid&quot;, primitive: undefined },
</code></pre>
<br>
<p>Unlike <code>bool-string</code>, for which we set <code>primitive</code> to <code>&quot;bool&quot;</code>, the <code>uuid</code> type doesn't have a <code>primitive</code>. That's because it doesn't correspond to any primitive type that's already in quicktype: it's a new type of its own.</p>
<p>More small differences await us in <a href="https://github.com/quicktype/quicktype/commit/22f0f6186c346609f86d2a55aee906ddb261d536">the commit that adds support for C#</a>. To start with, <code>uuid</code> has been added to <code>isValueType</code>:</p>
<pre><code class="language-javascript">return [&quot;integer&quot;, &quot;double&quot;, &quot;bool&quot;, &quot;enum&quot;, &quot;date-time&quot;, &quot;uuid&quot;].indexOf(t.kind) &gt;= 0;
</code></pre>
<br>
<p>That's needed because the C# type for UUIDs, <code>Guid</code>, is a value type in C#. We didn't have to do this for booleans because we didn't introduce a new type in C#: <code>bool</code> was already there. Speaking of <code>Guid</code>, there's a new case that introduces it in <code>csTypeForTransformedStringType</code>:</p>
<pre><code class="language-javascript">if (t.kind === &quot;uuid&quot;) {
    return &quot;Guid&quot;;
}
</code></pre>
<br>
<p>One last little change that we didn't see with booleans above is that <code>Guid</code> is now a &quot;forbidden name&quot; for the global namespace, which essentially means that quicktype won't name a C# class <code>Guid</code>, which would result in a name collision:</p>
<pre><code class="language-javascript">protected forbiddenNamesForGlobalNamespace(): string[] {
   return [&quot;QuickType&quot;, &quot;Type&quot;, &quot;System&quot;, &quot;Console&quot;, &quot;Exception&quot;, &quot;DateTimeOffset&quot;, &quot;Guid&quot;];
}
</code></pre>
<br>
<p>In <a href="https://github.com/quicktype/quicktype/commit/7f6a3d315d368d4e7501fc38ff8a0d730095fa55">the Python commit</a> we see similar changes, in particular a new case in <code>pythonType</code> to produce the <code>UUID</code> Python type:</p>
<pre><code class="language-javascript">if (transformedStringType.kind === &quot;uuid&quot;) {
    return this.withImport(&quot;uuid&quot;, &quot;UUID&quot;);
}
</code></pre>
<br>
<p>The <code>withImport</code> invocation returns <code>UUID</code> and <code>import</code>s the <code>uuid</code> package. The commit adds an identical case in <code>typeObject</code>, which returns the Python type object so the generated code can check whether a given value is an instance of that type.</p>
<p>The rest of the changes are very similar to those for booleans.</p>
<h4 id="whatwegetforfree">What we get for free</h4>
<p>We only had to implement converting individual values, but data transformers use that building block to give us a lot more for free. To illustrate, let's <a href="https://app.quicktype.io?share=xdHmPw3FR68Ao6EzX59g">quicktype this JSON input</a>:</p>
<pre><code class="language-json">{
    &quot;boolOrInts&quot;: [&quot;true&quot;, 123]
}
</code></pre>
<br>
<p>quicktype generates this type for the array items of <code>foo</code>, which is a union of boolean and integer:</p>
<pre><code class="language-csharp">    public partial struct BoolOrInt
    {
        public bool? Bool;
        public long? Integer;

        public static implicit operator BoolOrInt(bool Bool) =&gt; new BoolOrInt { Bool = Bool };
        public static implicit operator BoolOrInt(long Integer) =&gt; new BoolOrInt { Integer = Integer };
    }
</code></pre>
<br>
<p>Taking a look at the code for converting array items we see these lines:</p>
<pre><code class="language-csharp">if (Boolean.TryParse(stringValue, out b))
{
   return new Foo { Bool = b };
}
</code></pre>
<br>
<p>This is an example of a consumer transformer: The consumer of this <code>ParseStringTransformer</code> is a <code>UnionInstantiationTransformer</code>, which generates code that takes the boolean value and makes a <code>Foo</code> out of it. There's much more to data transformers than this, a lot of which we'll get to in a future blog post.</p>
<h4 id="howtocontribute">How to contribute</h4>
<p><a href="https://github.com/quicktype/quicktype">quicktype is Open Source</a>. If you'd like to see it improve, please consider contributing. When it comes to TSTs, there are two kinds of contributions that would be very helpful:</p>
<ul>
<li>
<p>Implement more TSTs. In particular <code>null</code>, floating point numbers, base64 blobs, and URLs. I hope I managed to convince you in this blog post that the scope of this is fairly manageable. It's a little tricky to understand at first, but once you do, you can contribute powerful features to quicktype, and we’re <a href="http://slack.quicktype.io/">always there to help</a>.</p>
</li>
<li>
<p>Implement data transformers for other languages. Right now transformers are only implemented in C# and Python, with no other language getting the benefit of TSTs, or other future enhancements to transformers. I won't lie: this is quite a challenge, but if you're up for one, please <a href="http://slack.quicktype.io/">talk to us on Slack</a>; we're always delighted to help.</p>
</li>
</ul>
</div>]]></content:encoded></item><item><title><![CDATA[quicktype news vol. 5]]></title><description><![CDATA[<div class="kg-card-markdown"><p>quicktype's first birthday, Python support, 'continuous mode' for VS Code, and a brand new product: <strong>autotune</strong></p>
<h2 id="quicktypeturnsone">quicktype turns one</h2>
<p>quicktype celebrated its first birthday on July 12th. In its first year, quicktype generated over 1.2 billion lines of code, by rough estimate. Read <a href="https://blog.quicktype.io/first-birthday/">the birthday post</a> for more about</p></div>]]></description><link>https://blog.quicktype.io/5/</link><guid isPermaLink="false">5b4bff7120ac8006ddecccb3</guid><category><![CDATA[news]]></category><dc:creator><![CDATA[David]]></dc:creator><pubDate>Mon, 16 Jul 2018 05:09:27 GMT</pubDate><content:encoded><![CDATA[<div class="kg-card-markdown"><p>quicktype's first birthday, Python support, 'continuous mode' for VS Code, and a brand new product: <strong>autotune</strong></p>
<h2 id="quicktypeturnsone">quicktype turns one</h2>
<p>quicktype celebrated its first birthday on July 12th. In its first year, quicktype generated over 1.2 billion lines of code, by rough estimate. Read <a href="https://blog.quicktype.io/first-birthday/">the birthday post</a> for more about quicktype's exciting first year.</p>
<h2 id="continuousmodeforvscode">Continuous mode for VS Code</h2>
<p>We recently released 'continuous mode' for quicktype within VS Code, which generates code continuously as you type:</p>
<p><img src="https://blog.quicktype.io/content/images/2018/07/2018-07-09-10.24.53.gif" alt="2018-07-09-10.24.53"></p>
<p>Install the <a href="https://marketplace.visualstudio.com/items?itemName=quicktype.quicktype">quicktype extension</a>, open a JSON file, then run the <code>Open quicktype for JSON</code> command to try it.</p>
<h2 id="pythonsupport">Python support</h2>
<p>Python is our latest language, with support for Python 2.7 through 3.7, including data classes and typing. In this screenshot, quicktype generates typed Python models from TypeScript:</p>
<p><img src="https://blog.quicktype.io/content/images/2018/07/python-shot.png" alt="python-shot"></p>
<p><a href="http://app.quicktype.io/?l=python">Try generating Python</a> in the quicktype web app.</p>
<h2 id="uuidandstringifiedintegerbooleandetection">UUID and stringified integer+boolean detection</h2>
<p>quicktype can now detect integers, booleans, and UUIDs (in addition to dates, times, and enums) within strings. quicktype will generate stronger types <em>and</em> code to convert JSON string values to the stronger types. In this screenshot, a strongly typed <code>Person</code> model is inferred from a JSON object with only string values:</p>
<p><img src="https://blog.quicktype.io/content/images/2018/07/Screen-Shot-2018-07-15-at-7.35.54-PM.png" alt="Screen-Shot-2018-07-15-at-7.35.54-PM"></p>
<p>These features are fully supported in Python and C# for now, and we're seeking contributors for other languages</p>
<h1 id="announcingautotune">Announcing autotune</h1>
<p>We've just launched <a href="https://autotune.xyz">autotune</a>, a tool that uses machine learning to automatically optimize apps and web sites. It's made for developers (rather than marketers) and has already improved quicktype in unexpected ways.</p>
<p>While building quicktype, we'd often come up with ideas for experiments for the quicktype web app and homepage. For example:</p>
<ul>
<li>Should we show code samples on our homepage?</li>
<li>How should we encourage users to sign up in the app?</li>
<li>What message should we ask users to tweet about quicktype?</li>
</ul>
<p>We found that implementing these tests with traditional A/B testing tools was not trivial—especially tests that affected application behavior or tests with many possible values—so we tended to only test straightforward and seemingly consequential facets.</p>
<p>We suspected that there were many, many more aspects of quicktype that could be optimized via A/B testing, <strong>so we created autotune to make adding tests and options as easy as adding a line of code</strong>.</p>
<p>For example, here's how we let autotune pick the best title for the button that opens the quicktype web app on <a href="https://quicktype.io">quicktype.io</a>:</p>
<pre><code class="language-javascript">import { autotune } from &quot;autotune&quot;;

function render() {
    let buttonTitle = autotune.oneOf(&quot;Open button title&quot;, [
      &quot;Launch&quot;,
      &quot;Try now&quot;,
      &quot;Open app&quot;,
      &quot;Generate code&quot;,
      &quot;Open quicktype&quot;
    ]);
    
    function launch() {
        autotune.complete();
        window.location.href = &quot;https://app.quicktype.io&quot;;
    }

    return &lt;Button onClick={launch} title={buttonTitle} /&gt;;
}
</code></pre>
<br>
<p>At first, autotune picked <code>buttonTitle</code> randomly, but soon it determined that <code>&quot;Generate code&quot;</code> performed best—14% better than <code>&quot;Open quicktype&quot;</code>—so autotune caused <code>&quot;Generate code&quot;</code> to be picked more often, increasing the number of users who open <a href="https://app.quicktype.io">app.quicktype.io</a> from <a href="https://quicktype.io">quicktype.io</a>.</p>
<p>Check out <a href="https://autotune.xyz">autotune.xyz</a> to try autotune for free today, and please let us know how it goes!</p>
</div>]]></content:encoded></item><item><title><![CDATA[Happy Birthday, quicktype!]]></title><description><![CDATA[<div class="kg-card-markdown"><p>Today quicktype is one year old. After generating one billion lines of code, here's a look back on quicktype's first year.</p>
<h2 id="howquicktypestarted">How quicktype started</h2>
<p>A year ago, I was writing some Swift to parse and represent JSON when I was struck by how mind-numbingly tedious the process was (especially before</p></div>]]></description><link>https://blog.quicktype.io/first-birthday/</link><guid isPermaLink="false">5b442f7d20ac8006ddeccca8</guid><dc:creator><![CDATA[David]]></dc:creator><pubDate>Thu, 12 Jul 2018 17:34:06 GMT</pubDate><content:encoded><![CDATA[<div class="kg-card-markdown"><p>Today quicktype is one year old. After generating one billion lines of code, here's a look back on quicktype's first year.</p>
<h2 id="howquicktypestarted">How quicktype started</h2>
<p>A year ago, I was writing some Swift to parse and represent JSON when I was struck by how mind-numbingly tedious the process was (especially before <code>Codable</code> was introduced in Swift 4). I had seen some simple JSON-to-code translators, but they were always buggy, had terrible UX, and were hard-coded for a single programming language.</p>
<p>&quot;Mark, I need your big brain,&quot; I said to my big-brained friend Mark, before explaining the problem and what I thought a good solution would be like: paste JSON on the left, instantly get lovely code in any language on the right, with functions for marshaling to-and-from JSON strings. The goal would be to generate the same code that a person would write by hand, so the style had to be impeccable and we'd have to infer intuitive names for types and properties.</p>
<p>Mark agreed it would be a fun project, so we started hacking, and within a day or two, the world got its <a href="https://blog.quicktype.io/first-look/">first look</a> at a crude prototype:</p>
<p><img src="https://blog.quicktype.io/content/images/2018/07/Screen-Shot-2018-07-09-at-9.19.11-PM.png" alt="Screen-Shot-2018-07-09-at-9.19.11-PM"></p>
<p>quicktype was implemented as 700 lines of purely-functional PureScript, generating C# and Go from an <a href="https://blog.quicktype.io/under-the-hood/">intermediate representation</a>. Here's the code that rendered C# classes:</p>
<pre><code class="language-haskell">renderCSharpClass :: IRClassData -&gt; Doc Unit
renderCSharpClass (IRClassData { names, properties }) = do
  line $ words [&quot;class&quot;, csNameStyle $ combineNames names]
  lines &quot;{&quot;
  indent do
    for_ (Map.toUnfoldable properties :: Array _) \(Tuple.Tuple pname ptype) -&gt; do
      line do
        string &quot;[JsonProperty(\&quot;&quot;
        string pname
        string &quot;\&quot;)]&quot;
      line do
        string &quot;public &quot;
        graph &lt;- getGraph
        string $ renderTypeToCSharp graph ptype
        words [&quot;&quot;, csNameStyle pname, &quot;{ get; set; }&quot;]
      blank
    
    -- TODO don't rely on 'TopLevel'
    when (names == Set.singleton &quot;TopLevel&quot;) do
      lines &quot;&quot;&quot;// Loading helpers
           public static TopLevel FromJson(string json) =&gt; JsonConvert.DeserializeObject&lt;TopLevel&gt;(json);
           public static TopLevel FromUrl(string url) =&gt; FromJson(new WebClient().DownloadString(url));&quot;&quot;&quot;
  lines &quot;}&quot;
</code></pre>
<br>
<p>Then we continuously deployed updates and new features for a year.</p>
<h2 id="quicktypetoday">quicktype today</h2>
<p>quicktype has come a long way in that time. quicktype now has:</p>
<ul>
<li>Generated over 1.2 billion lines of code, by rough estimate. In San Francisco, you'd have to hire 76 developers at a cost of $7.9 million to write this code, assuming no sick days and all programmers type 40 WPM for 6 hours per day!</li>
<li>30k lines of TypeScript in <a href="https://github.com/quicktype/quicktype">core libraries</a></li>
<li>13k lines of TypeScript in the web app</li>
<li>Support for C#, Go, Rust, C++, Objective-C, Java, TypeScript, JavaScript, Flow, Swift, Kotlin, Elm, JSON Schema, Ruby, and now Python</li>
<li>Support for GraphQL, JSON Schema, and TypeScript <em>as input</em>, so you can more formally specify desired output types</li>
<li>Many language-specific options, like typesafe HTTP request handlers in Swift or runtime type checking in JavaScript</li>
<li>Integer, enum, and map inference</li>
<li>Stringified number, boolean, date, and UUID inference with automatic parsing in C# and Python</li>
<li>Extensions for Xcode, VSCode, and Visual Studio</li>
</ul>
<p>We recently released 'continuous mode' for the <a href="https://marketplace.visualstudio.com/items?itemName=quicktype.quicktype">VSCode extension</a>, which generates code from JSON, schema, and TypeScript as you type:</p>
<p><img src="https://blog.quicktype.io/content/images/2018/07/2018-07-09-10.24.53.gif" alt="2018-07-09-10.24.53"></p>
<p>Python is our latest language, with support for Python 2.7 through 3.7, including data classes and typing:<br>
<a href="https://app.quicktype.io?share=eoFd3wjtu3uUUV61RmpY"><img src="https://blog.quicktype.io/content/images/2018/07/Screen-Shot-2018-07-12-at-9.31.48-AM.png" alt="Screen-Shot-2018-07-12-at-9.31.48-AM"></a></p>
<p>If you look carefully at the Python above*, you'll notice some subtle sophistications:</p>
<ul>
<li><code>people</code> is inferred to be a map using a <a href="https://blog.quicktype.io/markov/">Markov chain</a> that discerns class property names from arbitrary keys</li>
<li><code>fav number</code> is legalized as <code>fav_number</code>, automatically translated to-and-from JSON, and stringified numbers are detected and parsed</li>
<li><code>has friends</code> is inferred as a sometimes-stringified boolean, and is automatically translated from <code>string</code> to <code>bool</code></li>
<li><code>class</code> is reserved in Python, so it's legalized as <code>person_class</code> and automatically translated</li>
<li><code>born</code> is inferred to be a date and automatically parsed as a <code>datetime</code></li>
<li><code>nickname</code> is inferred as optional, and expressed as <code>Optional[str]</code></li>
</ul>
<p><small>* quicktype generates additional code to implement the automatic translations, omitted from the screenshot</small></p>
<p>As you can see, quicktype has evolved into something quite powerful from its simple beginnings.</p>
<h2 id="thankyou">Thank you!</h2>
<p>Thank you for using quicktype and giving us feedback! Nothing motivates us more than interacting with you on <a href="https://twitter.com/quicktypeio">Twitter</a>, <a href="https://github.com/quicktype/quicktype">GitHub</a>, Intercom, or <a href="http://slack.quicktype.io">Slack</a>. If you'd like to support our work, please blog, screencast, tweet, or demo quicktype to your friends. 😊</p>
</div>]]></content:encoded></item><item><title><![CDATA[Customizing quicktype]]></title><description><![CDATA[<div class="kg-card-markdown"><p>In this post I’ll show you how to customize quicktype’s output.  Suppose we’re building a mobile game in C# that the player can pick up on their Android phone in the morning, continue in their web browser in the afternoon and finish on their iPad in the</p></div>]]></description><link>https://blog.quicktype.io/customizing-quicktype/</link><guid isPermaLink="false">5b3c34f120ac8006ddeccca1</guid><category><![CDATA[how-to]]></category><category><![CDATA[internals]]></category><dc:creator><![CDATA[Mark]]></dc:creator><pubDate>Thu, 05 Jul 2018 15:17:03 GMT</pubDate><content:encoded><![CDATA[<div class="kg-card-markdown"><p>In this post I’ll show you how to customize quicktype’s output.  Suppose we’re building a mobile game in C# that the player can pick up on their Android phone in the morning, continue in their web browser in the afternoon and finish on their iPad in the evening.  We have to send the state of the game over the network to a server, which is written in Go, and we’d like to use JSON to serialize and deserialize the state.  quicktype already does a great job generating classes with serialization functionality for us, but we have a few extra requirements for the C# code:</p>
<ol>
<li>
<p>Some of the types will represent objects in the game, so quicktype will have to generate them as subclasses of <code>GameObject</code>.</p>
</li>
<li>
<p>We'd like to specify default values for some properties, such as the hit points of a player or monster. We want quicktype to generate those property assignments.</p>
</li>
</ol>
<p>Out of the box quicktype has neither of those two features, so we'll implement them in this blog post, making quicktype generate customized C# code from a JSON Schema model.</p>
<p>Before writing code to generate other code, we should design the desired generated code by hand to see what works and what doesn't, and to have a more specific idea of what the generated code should look like.  Here is the code we want quicktype to generate for us:</p>
<pre><code class="language-csharp">public partial class Player : GameObject
{
    public long HitPoints { get; set; } = 100;
    public string Name { get; set; } = &quot;Emmerich&quot;;
    public Position Position { get; set; }
}

public partial class Position
{
    public double X { get; set; }
    public double Y { get; set; }
}
</code></pre>
<br>
<p>As you can see, the <code>Player</code> class is a subclass of <code>GameObject</code> while <code>Position</code> is not.  The properties <code>HitPoints</code> and <code>Name</code> in <code>Player</code> also have default values.  quicktype can generate neither of those two out of the box, but it's customizable enough to make it happen.</p>
<p>This is the JSON Schema definition that we would like to use as an input to quicktype to generate the sample code above:</p>
<pre><code class="language-json">{
    &quot;$schema&quot;: &quot;http://json-schema.org/draft-06/schema#&quot;,
    &quot;$ref&quot;: &quot;#/definitions/Player&quot;,
    &quot;definitions&quot;: {
        &quot;Player&quot;: {
            &quot;type&quot;: &quot;object&quot;,
            &quot;properties&quot;: {
                &quot;name&quot;: { &quot;type&quot;: &quot;string&quot;, &quot;default&quot;: &quot;Emmerich&quot; },
                &quot;position&quot;: { &quot;$ref&quot;: &quot;#/definitions/Coordinates&quot; },
                &quot;hitPoints&quot;: { &quot;type&quot;: &quot;integer&quot;, &quot;default&quot;: 100 }
            },
            &quot;required&quot;: [&quot;name&quot;, &quot;position&quot;, &quot;hitPoints&quot;],
            &quot;additionalProperties&quot;: false,
            &quot;gameObject&quot;: true
        },
        &quot;Coordinates&quot;: {
            &quot;type&quot;: &quot;object&quot;,
            &quot;properties&quot;: {
                &quot;x&quot;: { &quot;type&quot;: &quot;number&quot; },
                &quot;y&quot;: { &quot;type&quot;: &quot;number&quot; }
            },
            &quot;required&quot;: [&quot;x&quot;, &quot;y&quot;],
            &quot;additionalProperties&quot;: false
        }
    }
}
</code></pre>
<br>
<p>The definition of the <code>Player</code> type has the property <code>gameObject</code>, which obviously isn't part of the JSON Schema standard, and both <code>name</code> and <code>hitPoints</code> have a <code>default</code> property.  The latter is part of JSON Schema, but quicktype currently ignores it.  We'll change that.</p>
<h4 id="usingquicktypeasalibrary">Using quicktype as a library</h4>
<p>We will use quicktype as a library and write our own main program that invokes it.  You can follow along in <a href="https://github.com/quicktype/quicktype-custom-csharp-example">this repo</a>.</p>
<p>To start out, we need the <a href="https://www.npmjs.com/package/quicktype-core"><code>quicktype-core</code> NPM package</a>.  To invoke quicktype, we need this main function:</p>
<pre><code class="language-javascript">import * as fs from &quot;fs&quot;;

import { quicktype, InputData, JSONSchemaInput, CSharpTargetLanguage } from &quot;quicktype-core&quot;;

async function main(program: string, args: string[]): Promise&lt;void&gt; {
    // Exactly one command line argument allowed, the name of the JSON Schema file.
    if (args.length !== 1) {
        console.error(`Usage: ${program} SCHEMA`);
        process.exit(1);
    }

    // The &quot;InputData&quot; holds all the sources of type information that we give to quicktype.
    const inputData = new InputData();
    const source = { name: &quot;Player&quot;, schema: fs.readFileSync(args[0], &quot;utf8&quot;) };
    // &quot;JSONSchemaInput&quot; is the class that reads JSON Schema and converts it into quicktype's
    // internal type representation (see https://blog.quicktype.io/under-the-hood/ for a
    // semi-outdated but still useful introduction to the IR).
    // The &quot;source&quot; object is in the form that &quot;JSONSchemaInput&quot; needs.
    await inputData.addSource(&quot;schema&quot;, source, () =&gt; new JSONSchemaInput(undefined));

    // &quot;CSharpTargetLanguage&quot; is the class for basic C# types.  Its subclass
    // &quot;NewtonsoftCSharpTargetLanguage&quot; also produces attributes for Newtonsoft's Json.NET,
    // but we don't need those for our game, so we work with the base class directly.
    // Because it's not specialized we have to give it three arguments, none of which are
    // actually needed in our simple application: The &quot;display name&quot; of the language, an
    // array of names by which we could specify it, were we using quicktype's CLI, and the
    // file extension for the language.
    const lang = new CSharpTargetLanguage(&quot;C#&quot;, [&quot;csharp&quot;], &quot;cs&quot;);

    // What we get back from running &quot;quicktype&quot; is the source code as an array of lines.
    const { lines } = await quicktype({ lang, inputData });

    for (const line of lines) {
        console.log(line);
    }
}

main(process.argv[1], process.argv.slice(2));
</code></pre>
<br>
<p>When we run this program with our JSON Schema input we get these basic classes:</p>
<pre><code class="language-csharp">public partial class Player
{
   public long HitPoints { get; set; }
   public string Name { get; set; }
   public Coordinates Position { get; set; }
}

public partial class Coordinates
{
   public double X { get; set; }
   public double Y { get; set; }
}
</code></pre>
<br>
<h4 id="ourowntargetlanguage">Our own target language</h4>
<p>Now that we have the basics working, let's build our own subclass of <code>CSharpTargetLanguage</code> and make it do something custom!  To be useful, we will have to subclass another class, as well: <code>CSharpRenderer</code>.  The <code>TargetLanguage</code> keeps all information about a specific language, such as its name, and what kinds of options its output can be customized with.  The <code>Renderer</code> is instantiated by the <code>TargetLanguage</code> with a specific set of options and only lives to produce output once.</p>
<p>Here is our first attempt at a <code>TargetLanguage</code>:</p>
<pre><code class="language-javascript">class GameCSharpTargetLanguage extends CSharpTargetLanguage {
    constructor() {
        // In the constructor we call the super constructor with fixed display name,
        // names, and extension, so we don't have to do it when instantiating the class.
        // Our class is not meant to be extensible in turn, so that's okay.
        super(&quot;C#&quot;, [&quot;csharp&quot;], &quot;cs&quot;);
    }

    // &quot;makeRenderer&quot; instantiates our &quot;GameCSharpRenderer&quot;.  &quot;cSharpOptions&quot; are the
    // values for the customization options for C#, and &quot;getOptionValues&quot; translates the
    // untyped string values to the typed values that the renderer likes.
    protected makeRenderer(renderContext: RenderContext, untypedOptionValues: { [name: string]: any }): CSharpRenderer {
        return new GameCSharpRenderer(this, renderContext, getOptionValues(cSharpOptions, untypedOptionValues));
    }
}

class GameCSharpRenderer extends CSharpRenderer {
    // We override the &quot;superclassForType&quot; method to make &quot;GameObject&quot; the superclass of all
    // class types.  We need to do the check for &quot;ClassType&quot; because quicktype also generates
    // classes for union types which we don't want to customize.
    protected superclassForType(t: Type): Sourcelike | undefined {
        if (t instanceof ClassType) {
            return &quot;GameObject&quot;;
        }
        return undefined;
    }
}
</code></pre>
<br>
<p>To use the <code>GameCSharpTargetLanguage</code> we have to instantiate it in <code>main</code>:</p>
<pre><code class="language-javascript">const lang = new GameCSharpTargetLanguage();
</code></pre>
<br>
<h4 id="selectivesubclassing">Selective subclassing</h4>
<p>To pass the information of whether a type is a game object from the JSON Schema to the renderer we need a feature of quicktype called &quot;type attributes&quot;.  A type attribute is a piece of information that can be attached to a type. For example, quicktype uses type attributes to store descriptions and potential names for types, and as we’ll see, they can also be used to extend code generation. Type attribute are opaque to the core systems of quicktype: quicktype passes them through, but otherwise leaves them alone, with the exception of invoking a few basic operations that all type attributes must support.</p>
<p>We will define a new kind of type attribute to indicate whether a type is a game object, and we’ll call it <code>GameObjectTypeAttributeKind</code>:</p>
<pre><code class="language-javascript">class GameObjectTypeAttributeKind extends TypeAttributeKind&lt;boolean&gt; {
   constructor() {
       // This name is only used for debugging purposes.
       super(&quot;gameObject&quot;);
   }

   // When two or more classes are combined, such as in a &quot;oneOf&quot; schema, the
   // resulting class is a game object if at least one of the constituent
   // classes is a game object.
   combine(attrs: boolean[]): boolean {
       return attrs.some(x =&gt; x);
   }

   // Type attributes are made inferred in cases where the given type
   // participates in a union with other non-class types, for example.  In
   // those cases, the union type does not get the attribute at all.
   makeInferred(_: boolean): undefined {
       return undefined;
   }

   // For debugging purposes only.  It shows up when quicktype is run with
   // with the &quot;debugPrintGraph&quot; option.
   stringify(isGameObject: boolean): string {
       return isGameObject.toString();
   }
}

const gameObjectTypeAttributeKind = new GameObjectTypeAttributeKind();
</code></pre>
<br>
<p>Our new attribute kind extends <code>TypeAttributeKind&lt;boolean&gt;</code>, which means that the value of one such attribute is just a <code>boolean</code>.  All we need to know, after all, is whether—<code>true</code>—or not—<code>false</code>—a type is a game object.  Notable things about the methods we override:</p>
<ul>
<li>
<p><code>makeInferred</code> is currently used only for naming types.  It has potential other uses, but we won't get into it here.  You'll almost always want to return <code>undefined</code> here.</p>
</li>
<li>
<p>quicktype sometimes needs to combine types with each other that are separate in the JSON Schema.  For example, we can't (yet) process unions of different class types, so when you try to create one with <code>oneOf</code> or <code>anyOf</code>, the two class types get combined into one, containing the union of the original classes' properties.  What happens to those two classes' type attributes is that they are combined with the method <code>combine</code>.  In our case, if any of the constituent types represent a game object, we'll make the resulting type represent one, too.</p>
</li>
</ul>
<p>Now that we have our type attribute kind, how do we get the actual attributes onto the types?  We need an attribute producer, which is a function that the JSON Schema input code calls on each schema type, and which can return one or more type attributes, or <code>undefined</code> if it doesn't apply to that type.  Here's the producer for our game object attribute:</p>
<pre><code class="language-javascript">// &quot;schema&quot; is the JSON object in the schema for the type it's being applied to.
// In the case of our &quot;Player&quot; type, that would be the object at &quot;definitions.Player&quot;
// in the schema.

// &quot;canonicalRef&quot; is the location in the schema of that type.  We only use it in an
// error message here.

// &quot;types&quot; is a set of JSON type specifiers, such as &quot;object&quot;, &quot;string&quot;, or
// &quot;boolean&quot;.  The reason it's a set and not just a single one is that one type
// within the schema can specify values of more than one JSON type.  For example,
// { &quot;type&quot;: [&quot;string&quot;, &quot;boolean&quot;] } is a JSON Schema for &quot;all strings and all
// booleans&quot;.
function gameObjectAttributeProducer(
    schema: JSONSchema,
    canonicalRef: Ref,
    types: Set&lt;JSONSchemaType&gt;
): JSONSchemaAttributes | undefined {
    // Booleans are valid JSON Schemas, too: &quot;true&quot; means &quot;all values allowed&quot; and
    // &quot;false&quot; means &quot;no values allowed&quot;.  In fact, the &quot;false&quot; for
    // additionalProperties in our schema is a case of the latter.  For that reason,
    // our producer could be called on a boolean, which we have to check for first.
    if (typeof schema !== &quot;object&quot;) return undefined;

    // Next we check whether the type we're supposed to produce attributes for even
    // allows objects as values.  If it doesn't, it's not our business, so we
    // return &quot;undefined&quot;.
    if (!types.has(&quot;object&quot;)) return undefined;

    // Now we can finally check whether our type is supposed to be a game object.
    let isGameObject: boolean;
    if (schema.gameObject === undefined) {
        // If it doesn't have the &quot;gameObject&quot; property, it isn't.
        isGameObject = false;
    } else if (typeof schema.gameObject === &quot;boolean&quot;) {
        // If it does have it, we make sure it's a boolean and use its value.
        isGameObject = schema.gameObject;
    } else {
        // If it's not a boolean, we throw an exception to let the user know
        // what's what.
        throw new Error(`gameObject is not a boolean in ${canonicalRef}`);
    }

    // Lastly, we generate the type attribute and return it, which requires a bit of
    // ceremony.  A producer is allowed to return more than one type attribute, so to
    // know which attribute corresponds to which attribute kind, it needs to be wrapped
    // in a &quot;Map&quot;, which is what &quot;makeAttributes&quot; does.  The &quot;forType&quot; specifies that
    // these attributes go on the actual types specified in the schema.  We won't go
    // into the other possibilities here.
    return { forType: gameObjectTypeAttributeKind.makeAttributes(isGameObject) };
}
</code></pre>
<br>
<p>To tell the <code>JSONSchemaInput</code> about our attribute producer, we pass it in as the second argument when we instantiate it in <code>main</code>:</p>
<pre><code class="language-javascript">await inputData.addSource(&quot;schema&quot;, source, () =&gt;
    new JSONSchemaInput(undefined, [gameObjectAttributeProducer])
);
</code></pre>
<br>
<p>That was quite a bit of work, and we're almost done.  The last thing we need to do is make our renderer look at the type attribute and only generate the <code>GameObject</code> superclass where we need it.  Here's the code required to do that:</p>
<pre><code class="language-javascript">protected superclassForType(t: Type): Sourcelike | undefined {
    if (!(t instanceof ClassType)) return undefined;

    // All the type's attributes
    const attributes = t.getAttributes();
    // The game object attribute, or &quot;undefined&quot;
    const isGameObject = gameObjectTypeAttributeKind.tryGetInAttributes(attributes);
    return isGameObject ? &quot;GameObject&quot; : undefined;
}
</code></pre>
<br>
<p>Apart from the boilerplate, which is a story for another time, this should be self-explanatory.  Our code now produces the superclass in the right places!</p>
<h4 id="defaultvalues">Default values</h4>
<p>The other feature we need are default values, which we'll implement with a second type attribute kind.  We will be lazy here: We'll only properly support default values for number, string, and boolean types, and we won't do any error handling for cases that don't work.  The way we're implementing it is by holding on to the default value JSON object and just stringifying it into the C# code.  The syntax for numbers, strings, and booleans is the same in JSON and C#, which is why this works, mostly.</p>
<p>Here is the type attribute kind, which stores a type's default value as an <code>any</code>:</p>
<pre><code class="language-javascript">class DefaultValueTypeAttributeKind extends TypeAttributeKind&lt;any&gt; {
    constructor() {
        super(&quot;propertyDefaults&quot;);
    }

    combine(attrs: any[]): any {
        // If types with default values are combined, they better have the same
        // default value!  We make sure of that here, and throw an exception if
        // they don't.
        const a = attrs[0];
        for (let i = 1; i &lt; attrs.length; i++) {
            if (a !== attrs[i]) {
                throw new Error(&quot;Inconsistent default values&quot;);
            }
        }
        return a;
    }

    makeInferred(_: any): undefined {
        return undefined;
    }

    stringify(v: any): string {
        return JSON.stringify(v.toObject());
    }
}

const defaultValueTypeAttributeKind = new DefaultValueTypeAttributeKind();
</code></pre>
<br>
<p>Again, we'll also need an attribute producer, which is pretty simple in this case:</p>
<pre><code class="language-javascript">function propertyDefaultsAttributeProducer(schema: JSONSchema): JSONSchemaAttributes | undefined {
    // booleans are valid JSON Schemas, too, but we won't produce our
    // attribute for them.
    if (typeof schema !== &quot;object&quot;) return undefined;

    // Don't make an attribute if there's no &quot;default&quot; property.
    if (typeof schema.default === undefined) return undefined;

    return { forType: defaultValueTypeAttributeKind.makeAttributes(schema.default) };
}
</code></pre>
<br>
<p>We make sure we're dealing with an object, that it has a <code>default</code> property, and if it does, we just take its value and make an attribute out of it.  Of course we also have to pass in the new producer function when we instantiate <code>JSONSchemaInput</code>.</p>
<p>How do we produce the C# code for this?  The <code>CSharpRenderer</code> has a method <code>propertyDefinition</code> which returns the code for a single property.  What we need to do is override it such that when that property has a default value, there's also an assignment <code>= &lt;default&gt;;</code> at the end:</p>
<pre><code class="language-csharp">protected propertyDefinition(p: ClassProperty, name: Name, c: ClassType, jsonName: string): Sourcelike {
    // Call &quot;CSharpRenderer&quot;'s &quot;propertyDefinition&quot; to get the code for the property
    // definition without the default value assignment.
    const originalDefinition = super.propertyDefinition(p, name, c, jsonName);
    // The property's type attributes
    const attributes = p.type.getAttributes();
    const v = defaultValueTypeAttributeKind.tryGetInAttributes(attributes);
    // If we don't have a default value, return the original definition
    if (v === undefined) return originalDefinition;
    // There is a default value, so stringify it and bolt it onto the original code
    // at the end.
    return [originalDefinition, &quot; = &quot;, JSON.stringify(v), &quot;;&quot;];
}
</code></pre>
<br>
<p>We're done!  Check out the <a href="https://github.com/quicktype/quicktype-custom-csharp-example">finished project on GitHub</a>.  If you'd like to apply this to your own use case and need any help whatsoever, please come <a href="https://slack.quicktype.io/">talk to us on Slack</a>.</p>
</div>]]></content:encoded></item><item><title><![CDATA[quicktype news vol. 4]]></title><description><![CDATA[<div class="kg-card-markdown"><p>Our biggest set of updates ever. Let's get right to it!</p>
<h2 id="newlanguages">New Languages</h2>
<ul>
<li><a href="https://app.quicktype.io/?l=objc">Objective-C</a> with no dependencies</li>
<li><a href="https://app.quicktype.io/?l=kotlin">Kotlin</a> via Klaxon</li>
<li><a href="https://app.quicktype.io/?l=rust">Rust</a></li>
<li><a href="https://app.quicktype.io/?l=ruby">Ruby</a> with runtime typechecking</li>
<li><a href="https://app.quicktype.io/?l=flow">Flow</a></li>
<li><a href="https://app.quicktype.io/?l=js">Vanilla JavaScript</a> with runtime typechecking</li>
</ul>
<h2 id="newcfeatures">New C# Features</h2>
<ul>
<li>Option to fail if required properties are missing from JSON.</li>
<li>Option to choose <code>Double</code> or <code>Decimal</code></li></ul></div>]]></description><link>https://blog.quicktype.io/4/</link><guid isPermaLink="false">5afdbd8820ac8006ddeccc9a</guid><category><![CDATA[news]]></category><dc:creator><![CDATA[David]]></dc:creator><pubDate>Thu, 17 May 2018 19:56:13 GMT</pubDate><content:encoded><![CDATA[<div class="kg-card-markdown"><p>Our biggest set of updates ever. Let's get right to it!</p>
<h2 id="newlanguages">New Languages</h2>
<ul>
<li><a href="https://app.quicktype.io/?l=objc">Objective-C</a> with no dependencies</li>
<li><a href="https://app.quicktype.io/?l=kotlin">Kotlin</a> via Klaxon</li>
<li><a href="https://app.quicktype.io/?l=rust">Rust</a></li>
<li><a href="https://app.quicktype.io/?l=ruby">Ruby</a> with runtime typechecking</li>
<li><a href="https://app.quicktype.io/?l=flow">Flow</a></li>
<li><a href="https://app.quicktype.io/?l=js">Vanilla JavaScript</a> with runtime typechecking</li>
</ul>
<h2 id="newcfeatures">New C# Features</h2>
<ul>
<li>Option to fail if required properties are missing from JSON.</li>
<li>Option to choose <code>Double</code> or <code>Decimal</code> for floating-point numbers.</li>
<li>Option to choose <code>Object</code> or <code>dynamic</code> for properties without type information.</li>
</ul>
<h2 id="newswiftfeatures">New Swift Features</h2>
<ul>
<li><code>URLSession</code> task extensions make it easier than ever to download API data as structs without any dependencies:</li>
</ul>
<pre><code class="language-swift">let task = URLSession.shared.pokedexTask(with: url) { pokedex, response, error in
  if let pokedex = pokedex {
    ...
  }
}
task.resume()
</code></pre>
<br>
<ul>
<li>Alamofire extensions add <a href="https://app.quicktype.io?share=ZHj6mlN89Hu0pPw98s9O">similar extensions</a> for working with Alamofire.</li>
<li>Option to specify a type name prefix.</li>
<li>Option to choose <code>internal</code> or <code>public</code> access level for creating library code.</li>
</ul>
<h2 id="draganddropmultiplefiles">Drag-and-drop Multiple Files</h2>
<p>Try dropping multiple JSON files into quicktype to generate a coherent set of types. quicktype will infer equivalent types across the samples to prevent duplicates.</p>
<p><img src="https://blog.quicktype.io/content/images/2018/05/drag-and-drop-quicktype.gif" alt="drag-and-drop-quicktype"></p>
<h2 id="sharequicktypeeasily">Share quicktype Easily</h2>
<p>The new <code>Share Link</code> button will generate a link to share your input and options:</p>
<p><img src="https://blog.quicktype.io/content/images/2018/05/share-link.png" alt="share-link"></p>
<p>This is a great way to help another developer generate code with quicktype, or to make a snapshot of quicktype to refer to later.</p>
<h2 id="downloadcodeaszip">Download Code as zip</h2>
<p>quicktype generates multiple files for languages like Objective-C and Java, so now you can click <code>Download Code</code> to get a zip containing many source files rather than creating separate files manually.</p>
<h2 id="quicktypeplaygrounds">quicktype Playgrounds</h2>
<script src="https://unpkg.com/quicktype-playground@1"></script>
<style>
.quicktype {
    display: none;
}
.quicktype-playground a {
   border: 0;
}
</style>
<p><a href="https://blog.quicktype.io/p/ba141e85-d55a-4fb6-9e78-5ffd6871b81f//playgrounds">quicktype playgrounds</a> allow you to embed quicktype in any webpage by including a single script and placing some sample JSON in a <code>&lt;div&gt;</code>. This is great for pages that display JSON because it allows visitors to immediately copy code to represent the data in their apps.</p>
<div class="quicktype" data-type-name="Pokedex" data-languages="Ruby C# Kotlin Java Swift">
{
  "pokemon": [
    {
      "id": 1,
      "num": "001",
      "name": "Bulbasaur",
      "img": "http://www.serebii.net/pokemongo/pokemon/001.png",
      "type": [ "Grass", "Poison" ],
      "weaknesses": [ "Fire", "Ice", "Flying", "Psychic" ],
      "next_evolution": [
        { "num": "002", "name": "Ivysaur" },
        { "num": "003", "name": "Venusaur" }
      ]
    },
    {
      "id": 2,
      "num": "002",
      "name": "Ivysaur",
      "img": "http://www.serebii.net/pokemongo/pokemon/002.png",
      "type": [ "Grass", "Poison" ],
      "weaknesses": [ "Fire", "Ice", "Flying", "Psychic" ],
      "prev_evolution": [
        { "num": "001", "name": "Bulbasaur" }
      ],
      "next_evolution": [
        { "num": "003", "name": "Venusaur" }
      ]
    }
  ]
}
</div>
<br>
<h2 id="typescriptinput">TypeScript Input</h2>
<p>For succinct, precise control over generated types, you can now use TypeScript as an <em>input</em> language. Here's <a href="https://app.quicktype.io?share=b5IucarBffjYfqi0esRr">an example</a> of an <code>AddressBook</code> type specified in TypeScript, then generated in every language quicktype supports.</p>
<h2 id="postmaninput">Postman Input</h2>
<p>You can quicktype an entire Postman Collection by dropping it into quicktype:</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/uVDAEQRA86o?rel=0&showinfo=0&start=38" frameborder="0" allowfullscreen></iframe>
<p><a href="http://blog.getpostman.com/2018/04/05/turn-your-postman-collection-into-models-with-quicktype-io/">Learn more</a> about this feature on the Postman blog.</p>
<h2 id="visualstudioandxcodeextensions">Visual Studio and Xcode Extensions</h2>
<p>Try our free &amp; open source <a href="https://marketplace.visualstudio.com/items?itemName=typeguard.quicktype-vs">Visual Studio</a> and <a href="https://itunes.apple.com/us/app/paste-json-as-code-quicktype/id1330801220?mt=12">Xcode</a> extensions. You can find the repos <a href="https://github.com/quicktype/quicktype-vs">here</a> and <a href="https://github.com/quicktype/quicktype-xcode">here</a>.</p>
<h2 id="improvementstoquicktypecorelibrary">Improvements to quicktype Core Library</h2>
<p>Better map inference using <a href="https://blog.quicktype.io/markov">Markov chains</a>.</p>
<ul>
<li>Support for more JSON Schema features, documentation as comments, better error reporting, better naming, renaming.</li>
</ul>
<p><strong>Extend a language or implement your own using quicktype as a library</strong></p>
<p>Did you know that quicktype is also a library? In fact, all quicktype apps (web, CLI, IDE extensions, and playgrounds) use the same open-source <code>quicktype</code> library from <code>npm</code>.</p>
<p>Use it from JavaScript by doing <code>npm i quicktype</code> then:</p>
<pre><code class="language-javascript">import { quicktype } from &quot;quicktype&quot;;
const result = quicktype({ ... });
</code></pre>
<br>
<p>Here are two examples of using quicktype as a library:</p>
<ul>
<li><a href="https://github.com/quicktype/quicktype-custom-csharp-example">Generating customized C#</a></li>
<li><a href="https://github.com/quicktype/quicktype-custom-java-example">Generating customized Java</a></li>
</ul>
<h1 id="thankyou">Thank you!</h1>
<p>Thank you for using quicktype. We love working on it and helping developers wrangle the world's messy JSON data. If you'd like to support us, please share quicktype by writing blog posts, making screencasts, demoing it at meetups, or just sharing it with friends &amp; colleagues.</p>
<p>As always, please let us know if there are any new features you'd find useful! <a href="http://slack.quicktype.io/">Say &quot;👋&quot; on Slack</a> if you'd like to get in touch with us, or just click the chat bubble in the lower-right. Thanks!</p>
</div>]]></content:encoded></item><item><title><![CDATA[Instantly generate Kotlin types and serializers from JSON]]></title><description><![CDATA[<div class="kg-card-markdown"><p>quicktype can now generate Kotlin types and serializers from JSON sample data. Here's the <a href="https://app.quicktype.io?share=jzdVcZp14dk1RPT9Ouca">Pokémon sample</a> running in a <a href="https://blog.quicktype.io/playgrounds/">quicktype playground</a>, demonstrating Kotlin, Java, and Swift code generated from the same sample JSON data:</p>
<script src="https://unpkg.com/quicktype-playground@1"></script>
<style>
.quicktype {
    display: none;
}
.quicktype-playground a {
   border: 0;
}
</style>
<div class="quicktype" data-type-name="Pokedex" data-languages="Kotlin Java Swift">
{
  "pokemon": [
    {
      "id": 1,
      "num": "001",
      "name": "Bulbasaur",
      "img": "http:</div></div>]]></description><link>https://blog.quicktype.io/kotlin/</link><guid isPermaLink="false">5af32e0d20ac8006ddeccc96</guid><dc:creator><![CDATA[David]]></dc:creator><pubDate>Wed, 09 May 2018 17:41:50 GMT</pubDate><media:content url="https://blog.quicktype.io/content/images/2018/05/Kotlin_logo_wordmark.jpg" medium="image"/><content:encoded><![CDATA[<div class="kg-card-markdown"><img src="https://blog.quicktype.io/content/images/2018/05/Kotlin_logo_wordmark.jpg" alt="Instantly generate Kotlin types and serializers from JSON"><p>quicktype can now generate Kotlin types and serializers from JSON sample data. Here's the <a href="https://app.quicktype.io?share=jzdVcZp14dk1RPT9Ouca">Pokémon sample</a> running in a <a href="https://blog.quicktype.io/playgrounds/">quicktype playground</a>, demonstrating Kotlin, Java, and Swift code generated from the same sample JSON data:</p>
<script src="https://unpkg.com/quicktype-playground@1"></script>
<style>
.quicktype {
    display: none;
}
.quicktype-playground a {
   border: 0;
}
</style>
<div class="quicktype" data-type-name="Pokedex" data-languages="Kotlin Java Swift">
{
  "pokemon": [
    {
      "id": 1,
      "num": "001",
      "name": "Bulbasaur",
      "img": "http://www.serebii.net/pokemongo/pokemon/001.png",
      "type": [ "Grass", "Poison" ],
      "weaknesses": [ "Fire", "Ice", "Flying", "Psychic" ],
      "next_evolution": [
        { "num": "002", "name": "Ivysaur" },
        { "num": "003", "name": "Venusaur" }
      ]
    },
    {
      "id": 2,
      "num": "002",
      "name": "Ivysaur",
      "img": "http://www.serebii.net/pokemongo/pokemon/002.png",
      "type": [ "Grass", "Poison" ],
      "weaknesses": [ "Fire", "Ice", "Flying", "Psychic" ],
      "prev_evolution": [
        { "num": "001", "name": "Bulbasaur" }
      ],
      "next_evolution": [
        { "num": "003", "name": "Venusaur" }
      ]
    }
  ]
}
</div>
<br>
<p>As usual, quicktype will:</p>
<ul>
<li>Infer nice <a href="https://blog.quicktype.io/little-big-detail-2-contextual-class-names/">class</a> and <a href="https://blog.quicktype.io/little-big-detail-1-perfect-property-names/">property</a> names</li>
<li>Generate convenient <code>fromJson</code> and <code>toJson</code> methods for top-level types, including top-level arrays and maps</li>
<li>Deduplicate types inferred to be the same</li>
<li>Detect enums and emit custom marshaling code for them</li>
<li>Detect heterogeneous JSON data and emit sealed classes with custom marshaling code to keep your Kotlin typesafe</li>
<li>Distinguish <code>Map&lt;String, *&gt;</code> from custom object types automatically using <a href="https://blog.quicktype.io/markov/">Markov chains</a></li>
</ul>
<p>We've initially targeted the <a href="https://github.com/cbeust/klaxon">Klaxon JSON library</a> and we invite the community to <a href="https://github.com/quicktype/quicktype">contribute support</a> for other libraries. This is quicktype's second JVM language and we expect <a href="https://github.com/quicktype/quicktype/pull/843">Scala support</a> to land soon!</p>
<p><a href="https://app.quicktype.io?share=jzdVcZp14dk1RPT9Ouca">Open this sample in quicktype</a>.</p>
</div>]]></content:encoded></item><item><title><![CDATA[Convert JSON to code on any webpage with quicktype playgrounds]]></title><description><![CDATA[<div class="kg-card-markdown"><p>Based on Kotlin playgrounds<sup class="footnote-ref"><a href="#fn1" id="fnref1">[1]</a></sup>, <strong>quicktype playgrounds</strong> allow you to embed quicktype in any webpage by including a single script and placing some sample JSON in a <code>&lt;div&gt;</code>. This is great for pages that display JSON because it allows visitors to immediately copy code to represent the data</p></div>]]></description><link>https://blog.quicktype.io/playgrounds/</link><guid isPermaLink="false">5aea26a520ac8006ddeccc94</guid><dc:creator><![CDATA[David]]></dc:creator><pubDate>Wed, 02 May 2018 21:39:39 GMT</pubDate><content:encoded><![CDATA[<div class="kg-card-markdown"><p>Based on Kotlin playgrounds<sup class="footnote-ref"><a href="#fn1" id="fnref1">[1]</a></sup>, <strong>quicktype playgrounds</strong> allow you to embed quicktype in any webpage by including a single script and placing some sample JSON in a <code>&lt;div&gt;</code>. This is great for pages that display JSON because it allows visitors to immediately copy code to represent the data in their apps.</p>
<script src="https://unpkg.com/quicktype-playground@1"></script>
<style>
.quicktype {
    display: none;
}
.quicktype-playground a {
   border: 0;
}
</style>
<p>To add a quicktype playground to any webpage, first add this <code>&lt;script&gt;</code> element:</p>
<pre><code class="language-html">&lt;script src=&quot;https://unpkg.com/quicktype-playground@1&quot;&gt;&lt;/script&gt;
</code></pre>
<br>
<p>Then add a <code>&lt;div class=&quot;quicktype&quot; /&gt;</code> containing some sample JSON:</p>
<pre><code class="language-html">&lt;div class=&quot;quicktype&quot; data-type-name=&quot;Person&quot;&gt;
{
  &quot;name&quot;: &quot;Bob&quot;,
  &quot;age&quot;: 99,
  &quot;friends&quot;: [&quot;Sue&quot;, &quot;Vlad&quot;]
}
&lt;/div&gt;
</code></pre>
<br>
<p>When the page loads, the <code>&lt;div&gt;</code> becomes an interactive widget with the ability to view the types for that JSON in every language quicktype supports:</p>
<div class="quicktype" data-type-name="Person">
{
    "name": "Bob",
    "age": 99,
    "friends": ["Sue", "Vlad"]
}
</div>
<br>
<p>You can specify a subset of languages to display with <code>data-languages</code>:</p>
<pre><code class="language-html">&lt;div class=&quot;quicktype&quot; data-type-name=&quot;Pokedex&quot; data-languages=&quot;C# Java Swift&quot;&gt;
{
  &quot;pokemon&quot;: [
    {
      &quot;id&quot;: 1,
      &quot;num&quot;: &quot;001&quot;,
      &quot;name&quot;: &quot;Bulbasaur&quot;,
      &quot;img&quot;: &quot;http://www.serebii.net/pokemongo/pokemon/001.png&quot;,
      &quot;type&quot;: [ &quot;Grass&quot;, &quot;Poison&quot; ],
      &quot;weaknesses&quot;: [ &quot;Fire&quot;, &quot;Ice&quot;, &quot;Flying&quot;, &quot;Psychic&quot; ],
      &quot;next_evolution&quot;: [
        { &quot;num&quot;: &quot;002&quot;, &quot;name&quot;: &quot;Ivysaur&quot; },
        { &quot;num&quot;: &quot;003&quot;, &quot;name&quot;: &quot;Venusaur&quot; }
      ]
    },
    ...
  ]
}
&lt;/div&gt;
</code></pre>
<br>
<div class="quicktype" data-type-name="Pokedex" data-languages="C# Java Swift">
{
  "pokemon": [
    {
      "id": 1,
      "num": "001",
      "name": "Bulbasaur",
      "img": "http://www.serebii.net/pokemongo/pokemon/001.png",
      "type": [ "Grass", "Poison" ],
      "weaknesses": [ "Fire", "Ice", "Flying", "Psychic" ],
      "next_evolution": [
        { "num": "002", "name": "Ivysaur" },
        { "num": "003", "name": "Venusaur" }
      ]
    },
    {
      "id": 2,
      "num": "002",
      "name": "Ivysaur",
      "img": "http://www.serebii.net/pokemongo/pokemon/002.png",
      "type": [ "Grass", "Poison" ],
      "weaknesses": [ "Fire", "Ice", "Flying", "Psychic" ],
      "prev_evolution": [
        { "num": "001", "name": "Bulbasaur" }
      ],
      "next_evolution": [
        { "num": "003", "name": "Venusaur" }
      ]
    }
  ]
}
</div>
<br>
<p>This is an experimental feature that we hope you find useful! We still need to:</p>
<ul>
<li>Remove code left over from Kotlin playgrounds</li>
<li>Remove unused dependencies–the script is currently large but should be able to shrink significantly</li>
<li>Add more quicktype features</li>
</ul>
<p>Please check out <a href="https://github.com/quicktype/quicktype-playground">quicktype/quicktype-playground</a> to file issues or send pull requests!</p>
<hr class="footnotes-sep">
<section class="footnotes">
<ol class="footnotes-list">
<li id="fn1" class="footnote-item"><p>See <a href="https://github.com/JetBrains/kotlin-playground">github.com/JetBrains/kotlin-playground</a> <a href="#fnref1" class="footnote-backref">↩︎</a></p>
</li>
</ol>
</section>
</div>]]></content:encoded></item><item><title><![CDATA[Swift Types from C#]]></title><description><![CDATA[Do you have a C# codebase with model classes for a JSON API? Did you ever have to use that API with another programming language, wishing there was a way to automatically convert your C# model to that other language? With quicktype and Json.NET, there is!]]></description><link>https://blog.quicktype.io/swift-types-from-csharp/</link><guid isPermaLink="false">5ae67a1220ac8006ddeccc8c</guid><category><![CDATA[how-to]]></category><dc:creator><![CDATA[Mark]]></dc:creator><pubDate>Mon, 30 Apr 2018 15:55:56 GMT</pubDate><media:content url="https://blog.quicktype.io/content/images/2018/04/cs-to-swift-1.png" medium="image"/><content:encoded><![CDATA[<div class="kg-card-markdown"><img src="https://blog.quicktype.io/content/images/2018/04/cs-to-swift-1.png" alt="Swift Types from C#"><p>Do you have a C# codebase with model classes for a JSON API?  Did you ever have to use that API with another programming language, wishing there was a way to automatically convert your C# model to that other language?  With <a href="https://quicktype.io">quicktype</a> and <a href="https://www.newtonsoft.com/json">Json.NET</a>, there is!</p>
<p>In this post I'll show you how to convert your C# model to Swift, but if you'd rather watch than read, here's a video that shows how to do it in one minute, for a model in <a href="https://github.com/shadowsocks/shadowsocks-windows">this Open Source project</a>:</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/i8BVfiP3BvQ?rel=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>
<p>One piece of the puzzle is Newtonsoft's JSON Schema package, which has a feature to <a href="https://www.newtonsoft.com/jsonschema/help/html/GenerateSchema.htm">generate a JSON Schema from a C# model class</a>.  That schema then serves as input to quicktype, which will generate the equivalent model classes in your favorite programming language.  These are the steps to swift success:</p>
<ul>
<li>
<p>Add the <a href="https://www.nuget.org/packages/Newtonsoft.Json.Schema/">Json.Schema NuGet package</a> to your project.</p>
</li>
<li>
<p>Put this code somewhere it will run.  As a one-off, you can just do it first thing in your <code>Main</code> method, like I showed in the video.  If you want the option to run it again, maybe because you foresee that the model might change, you might even want to make a separate project just to run it:</p>
</li>
</ul>
<pre><code class="language-csharp">var generator = new JSchemaGenerator();
var schema = generator.Generate(typeof(MyModelClass));
File.WriteAllText(&quot;schema.json&quot;, schema.ToString());
</code></pre>
<br>
<ul>
<li>Run the code.  You should now have a <code>schema.json</code> file that you can copy and paste into <a href="https://app.quicktype.io">quicktype</a>.  Pick whichever programming language you need the model in, and witness the magic!</li>
</ul>
</div>]]></content:encoded></item><item><title><![CDATA[Little Big Detail #3: Detecting Maps]]></title><description><![CDATA[In this post we show how quicktype uses Markov chains to do decide which JSON represents a class and which JSON represents a map, so it can generate the ideal code for any JSON.]]></description><link>https://blog.quicktype.io/markov/</link><guid isPermaLink="false">5a92225d57550e06e15f21b4</guid><category><![CDATA[little-big-details]]></category><category><![CDATA[internals]]></category><dc:creator><![CDATA[Mark]]></dc:creator><pubDate>Mon, 05 Mar 2018 22:16:38 GMT</pubDate><media:content url="https://blog.quicktype.io/content/images/2018/03/sushi-taco-2.png" medium="image"/><content:encoded><![CDATA[<div class="kg-card-markdown"><img src="https://blog.quicktype.io/content/images/2018/03/sushi-taco-2.png" alt="Little Big Detail #3: Detecting Maps"><p><a href="https://blog.quicktype.io/tag/little-big-details/">Little Big Details</a> are the subtle niceties that <a href="https://quicktype.io">quicktype</a> takes care of when turning your JSON into lovely, readable code. This Little Big Detail is about how quicktype decides whether a JSON object should be represented as a class or a map.</p>
<h4 id="theproblem">The problem</h4>
<p>Suppose you're writing an app that uses the Bitcoin blockchain and it downloads data like this:</p>
<pre><code class="language-json">{
    &quot;0000000000000000000e222e4e7afc29c49f6398783a94c846dee2e13c6408f5&quot;: {
        &quot;size&quot;: 969709,
        &quot;height&quot;: 510599,
        &quot;difficulty&quot;: 3007383866429.732,
        &quot;previous&quot;: &quot;000000000000000000552a7783efd39eaa1c5ff6789e21a0bbe7547bc454fced&quot;
	},
	&quot;000000000000000000552a7783efd39eaa1c5ff6789e21a0bbe7547bc454fced&quot;: {
	    &quot;size&quot;: 991394,
        &quot;height&quot;: 510598,
        &quot;difficulty&quot;: 3007383866429.732,
        &quot;previous&quot;: &quot;00000000000000000043aba4c065d4d92aec529566287ebec5fe9010246c9589&quot;
	},
	&quot;00000000000000000043aba4c065d4d92aec529566287ebec5fe9010246c9589&quot;: {
        &quot;size&quot;: 990527,
        &quot;height&quot;: 510597,
        &quot;difficulty&quot;: 3007383866429.732,
        &quot;previous&quot;: &quot;00000000000000000009025b9e95911a4dc050de129ea4eb5e40ef280751a0cb&quot;
	}
}
</code></pre>
<br>
<p>How would you represent this data as a type in your program? Here’s a naive translation of the JSON into Swift types:</p>
<pre><code class="language-swift">struct Blocks {
  let _0000000000000000000e222e4e7afc29c49f6398783a94c846dee2e13c6408f5: Block
  let _00000000000000000043aba4c065d4d92aec529566287ebec5fe9010246c9589: Block
  let _00000000000000000009025b9e95911a4dc050de129ea4eb5e40ef280751a0cb: Block
}

struct Block {
    let size, height: Int
    let difficulty: Double
    let previous: String
}
</code></pre>
<br>
<p>Is this the Swift you would write? No, of course not! How about:</p>
<pre><code class="language-swift">typealias Blocks = [String: Block] // a.k.a. Dictionary&lt;String, Block&gt;

struct Block {
    let size, height: Int
    let difficulty: Double
    let previous: String
}
</code></pre>
<br>
<p>That's more like it! We're faced with this decision because JSON syntax doesn’t differentiate maps from classes—they both just look like:</p>
<pre><code class="language-json">{ &quot;x&quot;: …, &quot;y&quot;: …, &quot;z&quot;: … }
</code></pre>
<br>
<p>quicktype must decide which JSON represents a class (fixed properties) and which JSON represents a map (dynamic keys) so it can generate the same code you would in the example above. In this post we’ll explain how quicktype uses Markov chains to do this. If you’d rather skip to examples of quicktype’s map detection in action, check out our <a href="https://app.quicktype.io/?gist=d21b7f79735d791ee31a47956b1afc0e&amp;l=swift&amp;just-types=true">map detection playground</a>.</p>
<h4 id="simplisticheuristicsformapdetection">Simplistic heuristics for map detection</h4>
<p>A first observation about maps is that their values are almost always the same type or &quot;homogeneous&quot;. In fact, in statically-typed programming languages maps <em>must</em> be homogeneous. Our first heuristic for map detection could be:</p>
<blockquote>
<p>If all values in a JSON object have the same type, consider it a map.</p>
</blockquote>
<p>Unfortunately this heuristic fails immediately:</p>
<pre><code class="language-json">{
    &quot;name&quot;: &quot;Jon&quot;,
    &quot;pet&quot;: &quot;Garfield&quot;
}
</code></pre>
<br>
<p>You'd probably want a class for that data even though all values are strings.</p>
<p>Another observation is that maps often have more keys than classes have properties; if a JSON object has 100 properties, all of which are strings, it's probably a map, so let's add another condition to our heuristic:</p>
<blockquote>
<p>If all values in a JSON object have the same type <u><em>and it has at least 20 properties</em></u>, consider it a map.</p>
</blockquote>
<p>This was the previous heuristic quicktype used. It was adequate for <a href="https://app.quicktype.io/?s=us-temperatures&amp;l=swift&amp;just-types=true">large, regular samples</a> but failed whenever a map had fewer than 20 keys, which happens all the time.</p>
<h4 id="aheuristicthatdecideslikeahumanprogrammerdoes">A heuristic that decides like a human programmer does</h4>
<p>Let's come back to our original Bitcoin example. Most developers would correctly deduce that the type for each block should be a <em>class</em>, but that the outer object should be a <em>map</em>. Our previous heuristic would fail in this case, since there are only three blocks in the map.</p>
<p>How are we as human programmers able to infer that this data is a map? One strong clue is that the names of the properties (e.g. <code>000000000000000...c846dee2e13c6408f5</code>) don't look like class property names. If only we could teach quicktype to look for this clue. Enter <a href="https://en.wikipedia.org/wiki/Markov_chain">Markov chains</a>!</p>
<h3 id="whatsamarkovchain">What's a Markov chain?</h3>
<p>If you’re a developer, you may know Markov chains as a way of <a href="https://filiph.github.io/markov/">generating apparently meaningful nonsense</a>, but they have many other important applications.</p>
<p>A Markov chain is a set of states and transitions among those states, where each transition has a probability. Transitions occur randomly, weighted by the probabilities.</p>
<p>For example, let's use a Markov chain to model what I’ll eat for lunch. On most days I eat sushi, but now and then I'll have tacos. We can model this with two states: 🍣 and 🌮. The transitions between these states give the probabilities for which food I'll eat the next day. There are four possible transitions:</p>
<ul>
<li>
<p>🍣 → 🍣: if I eat sushi today, what's the likelihood I'll eat sushi tomorrow?  <mark>Let's say 85%</mark>.</p>
</li>
<li>
<p>🍣 → 🌮: if I eat sushi today, how likely am I to have tacos tomorrow? <mark>This must be 15%</mark>, since I only eat either sushi or tacos, and we already know what the probability is for sushi.</p>
</li>
<li>
<p>🌮 → 🍣: if I eat tacos today, what’s the likelihood I’ll eat sushi tomorrow?  <mark>Let's say 60%</mark>.</p>
</li>
<li>
<p>🌮 → 🌮: by similar reasoning, <mark>this must be 40%</mark>.</p>
</li>
</ul>
<img src="https://blog.quicktype.io/content/images/2018/03/sushi-taco-1.png" width="50%" alt="Little Big Detail #3: Detecting Maps">
<p>If you run this model you could get this sequence:</p>
<p>🍣 🍣 🍣 🍣 🍣 🍣 🍣 🍣 🌮 🌮 🍣 🍣 🍣 🍣 🍣 🍣 🍣 🌮 🌮 🌮 🍣 🌮 🌮 🌮 🌮 🍣 🍣 🍣</p>
<p>Yum! So how does this relate to detecting maps versus classes in JSON? What do you notice about the following sequence:</p>
<p>🌮 🌮 🍣 🌮 🌮 🍣 🌮 🌮 🌮 🌮 🍣 🌮 🌮 🌮 🌮 🍣 🍣 🌮 🌮 🌮 🍣 🌮 🌮 🌮 🌮 🌮 🌮 🍣</p>
<p>If you had to guess, would you say it's more or less likely that this sequence was produced by the same Markov chain? In other words, is it more or less likely that the second sequence is what I ate for lunch last month?</p>
<h3 id="markovchainsinquicktype">Markov chains in quicktype</h3>
<p>Consider a Markov chain for English words that looks at three letters at a time. Our state is the first two letters of any three-letter sequence, and our transitions give the probabilities for each possible third letter, given the first two.</p>
<p>For example, if the two letters are <code>qu</code>, then there is a high-probability transition for the letter <code>i</code> because many English words contain  <code>qui</code> (e.g. <code>acquire</code>, <code>colloquial</code>, <code>equip</code>).  On the other hand, the probability of a transition for <code>j</code> is zero, because no English word contains <code>quj</code>.  What's the state that <code>qu</code> transitions to for <code>i</code>?  It's <code>ui</code>, since we look at two characters at a time.</p>
<img src="https://blog.quicktype.io/content/images/2018/03/qu.png" width="90%" alt="Little Big Detail #3: Detecting Maps">
<p>Rather than using the Markov chain to generate pseudo-English words, we can feed it a sequence of letters, look at the probabilities of the transitions that would have produced that sequence, then use these probabilities to judge whether the sequence &quot;behaves&quot; like an English word. We do this by comparing the average<sup class="footnote-ref"><a href="#fn1" id="fnref1">[1]</a></sup> transition probability to what we would expect from an English word.</p>
<p><mark>Explore transition probabilities by typing in the widget below.</mark> The color of each letter corresponds to its probability given its two predecessors (<span style="color:green;">green</span> is likely, <span style="color:red;">red</span> is unlikely, and the first letters are white because they don't have predecessors). The outer color gives the average probability—our judgement for whether the word is English:</p>
<iframe src="https://quicktype.github.io/markov-react/" title="iframe example 1" width="100%" height="120"><p>Your browser does not support iframes.</p></iframe>
<br>
<p>Actually, the Markov chain used for this widget<sup class="footnote-ref"><a href="#fn2" id="fnref2">[2]</a></sup> is not built for detecting English, but rather for detecting class property names.  In fact, <mark>it's the same Markov chain quicktype uses to judge whether a JSON property name is a class property or a map key</mark>.  JSON objects usually have more than one property, though, so quicktype averages the probabilities of all property names in a given JSON object. Also, assuming JSON objects with fewer properties are more likely to be classes, quicktype allows property names to be a bit “weirder” when there are fewer of them<sup class="footnote-ref"><a href="#fn3" id="fnref3">[3]</a></sup>.</p>
<p>How did I arrive at the probability threshold for determining class property names? Ideally I'd have access to all the JSON that ever has been, and ever will be produced, and enough computing power to tally up all probabilities, but for now I wrote <a href="https://github.com/quicktype/quicktype/blob/master/test/generate-markov-corpus.py">a little script</a> that generates a million simulated property names using an English dictionary and a list of acronyms:</p>
<pre><code class="language-text">pseudoscarusEEPROM
Undisappointed12
Wmv Outbabble
complexionlessDingledangle
marchpane_gb_5
horsebacker79
_canineTentacle
perigynium caq 8
noctambulousGuardable
_INDICANT_AV_9
...
</code></pre>
<br>
<p>See map detection in action in our <a href="https://app.quicktype.io/?gist=6fc8b13b26d892bda95dae15f2f16bbd&amp;l=swift&amp;just-types=true">map detection playground</a>.</p>
<h4 id="whatifitfails">What if it fails?</h4>
<p>If quicktype still fails to identify your JSON object correctly, here's what you can do:</p>
<ul>
<li>
<p>If your object should be a class but quicktype thinks it's a map, you can disable map detection:<br>
<img src="https://blog.quicktype.io/content/images/2018/02/turn-off-maps.gif" width="100%" alt="Little Big Detail #3: Detecting Maps"></p>
</li>
<li>
<p>If quicktype thinks your object is a class when it should be a map, a bit more work is needed. The easiest way to correct this is to trick quicktype by making the property names look &quot;weird&quot;:<br>
<img src="https://blog.quicktype.io/content/images/2018/02/making-a-map.gif" width="100%" alt="Little Big Detail #3: Detecting Maps"></p>
</li>
</ul>
<p>If you want total control over the types generated by quicktype, you can always output JSON Schema, correct the schema, then use the schema as the input to quicktype. This is the <a href="https://www.youtube.com/watch?v=ZpaMIQQxY68&amp;t=797s">workflow we recommend</a> for using quicktype in general.</p>
<h4 id="futureimprovements">Future improvements</h4>
<p>Here are a few areas where we can improve map detection even further, and we’d love help from contributors on any of them:</p>
<ul>
<li>
<p>quicktype should take the length of JSON property names into account.  If a property name is a whole English sentence, that object is likely not a class.</p>
</li>
<li>
<p>English is not the only language in the world!  Right now, Mandarin is Greek to quicktype (and so is Greek).  Maybe quicktype needs to classify the JSON's &quot;language&quot; first and run a different Markov chain depending on the language? Or maybe a single Markov chain trained on more languages could do the trick?  Where do we get training data?</p>
</li>
<li>
<p>Another clue in the Bitcoin JSON is that the map values are complex (Bitcoin objects in this case). Some classes have relatively many string properties, but it's less common to find classes with lots of array, class, or map properties.</p>
</li>
<li>
<p>If quicktype sees more than one sample for the same type, and they have few shared property names, that makes that type more likely to be a map.</p>
</li>
<li>
<p>Some common forms of map keys are not easy for a Markov chain to detect, but can be covered easily with regular expressions.  Email addresses are an example.</p>
</li>
</ul>
<p>If you’re interested in working on these problems, please come <a href="http://slack.quicktype.io">talk to us on Slack</a> and check out <a href="https://github.com/quicktype/quicktype">quicktype on GitHub</a>. Thanks!</p>
<hr class="footnotes-sep">
<section class="footnotes">
<ol class="footnotes-list">
<li id="fn1" class="footnote-item"><p>With probabilities we can't just take the arithmetic mean of our <em>n</em> individual probabilities—we need the <a href="https://en.wikipedia.org/wiki/Geometric_mean">geometric mean</a>, which is the <em>nth</em> root of their product. <a href="#fnref1" class="footnote-backref">↩︎</a></p>
</li>
<li id="fn2" class="footnote-item"><p>Explore the Markov widget further at <a href="https://github.com/quicktype/markov-react">github.com/quicktype/markov-react</a>. <a href="#fnref2" class="footnote-backref">↩︎</a></p>
</li>
<li id="fn3" class="footnote-item"><p>The <a href="https://github.com/quicktype/quicktype/blob/fc33db2830c1f6e1a2f016821a7140f3293274af/src/InferMaps.ts#L32">details</a> of that are not very scientific. <a href="#fnref3" class="footnote-backref">↩︎</a></p>
</li>
</ol>
</section>
</div>]]></content:encoded></item><item><title><![CDATA[Typesafe API calls in Swift: Generating Alamofire Handlers with quicktype]]></title><description><![CDATA[<div class="kg-card-markdown"><p><a href="https://github.com/Alamofire/Alamofire">Alamofire</a> is an elegant HTTP networking library that makes working with JSON APIs in Swift a breeze. <a href="https://app.quicktype.io/?l=swift&amp;initializers=false&amp;alamofire=true">quicktype</a> makes Alamofire even more awesome by generating extensions and Codables for typesafe API calls.</p>
<p>Here's Alamofire's canonical example of handling a JSON API response:</p>
<pre><code class="language-swift">Alamofire.request(&quot;https://httpbin.org/get&quot;</code></pre></div>]]></description><link>https://blog.quicktype.io/alamofire/</link><guid isPermaLink="false">5a98662820ac8006ddeccc74</guid><category><![CDATA[how-to]]></category><dc:creator><![CDATA[David]]></dc:creator><pubDate>Thu, 01 Mar 2018 20:56:25 GMT</pubDate><content:encoded><![CDATA[<div class="kg-card-markdown"><p><a href="https://github.com/Alamofire/Alamofire">Alamofire</a> is an elegant HTTP networking library that makes working with JSON APIs in Swift a breeze. <a href="https://app.quicktype.io/?l=swift&amp;initializers=false&amp;alamofire=true">quicktype</a> makes Alamofire even more awesome by generating extensions and Codables for typesafe API calls.</p>
<p>Here's Alamofire's canonical example of handling a JSON API response:</p>
<pre><code class="language-swift">Alamofire.request(&quot;https://httpbin.org/get&quot;).responseJSON { response in
    if let json = response.result.value {
        // json is of type Any, so we must cast and use dictionary indexers
        let data = json as! [String: Any]
        let headers = data[&quot;headers&quot;] as! [String: String]
        print(headers[&quot;Accept-Language&quot;])
    }
}
</code></pre>
<br>
<p>Unfortunately, as you can see, you're still left with <code>json: Any</code>, a dynamic value that you must cast and awkwardly introspect for the data you care about.</p>
<p><a href="https://app.quicktype.io/?l=swift&amp;initializers=false&amp;alamofire=true">quicktype</a> can generate statically-typed Alamofire response handlers along with <code>Codable</code> structs from JSON, allowing us to rewrite the above sample like this:</p>
<pre><code class="language-swift">Alamofire.request(&quot;https://httpbin.org/get&quot;).responseHTTPBinGet { response in
    if let json = response.result.value {
        print(json.headers.acceptLanguage)
    }
}
</code></pre>
<br>
<h2 id="howitsdone">How it's done</h2>
<p>You can use the <a href="https://www.npmjs.com/package/quicktype">quicktype CLI</a> or <a href="https://app.quicktype.io/?l=swift&amp;initializers=false&amp;alamofire=true">app.quicktype.io</a> to generate Alamofire extensions and Codable structs directly from the API endpoint:</p>
<pre><code class="language-shell">$ quicktype https://httpbin.org/get --alamofire -o HTTPBinGet.swift
</code></pre>
<br>
<p>quicktype generates the following <code>Codable</code> type for this API:</p>
<pre><code class="language-swift">struct HTTPBinGet: Codable {
    let args: Args
    let headers: Headers
    let origin, url: String
}

struct Args: Codable {
}

struct Headers: Codable {
    let accept, acceptEncoding, acceptLanguage, connection: String
    let host, upgradeInsecureRequests, userAgent: String

    enum CodingKeys: String, CodingKey {
        case accept = &quot;Accept&quot;
        case acceptEncoding = &quot;Accept-Encoding&quot;
        case acceptLanguage = &quot;Accept-Language&quot;
        case connection = &quot;Connection&quot;
        case host = &quot;Host&quot;
        case upgradeInsecureRequests = &quot;Upgrade-Insecure-Requests&quot;
        case userAgent = &quot;User-Agent&quot;
    }
}
</code></pre>
<br>
<p>And Alamofire extensions to handle the API response:</p>
<pre><code class="language-swift">extension DataRequest {
    // ...

    @discardableResult
    func responseHTTPBinGet(
        queue: DispatchQueue? = nil,
        completionHandler: @escaping (DataResponse&lt;HTTPBinGet&gt;) -&gt; Void)
        -&gt; Self {
            return responseDecodable(queue: queue, completionHandler: completionHandler)
    }
}
</code></pre>
<br>
<p>The code generated by quicktype allows you to do a statically-typed Alamofire request, getting the benefit of type-safety and code completion on your response data!</p>
<pre><code class="language-swift">Alamofire.request(&quot;https://httpbin.org/get&quot;).responseHTTPBinGet { response in
    if let json = response.result.value {
*         // json is an instance of HTTPBinGet
        print(json.headers.acceptLanguage)
    }
}
</code></pre>
<br>
<p><a href="https://app.quicktype.io/?l=swift&amp;initializers=false&amp;alamofire=true">Try this feature in your browser.</a></p>
</div>]]></content:encoded></item><item><title><![CDATA[Paste JSON as code in Xcode and Visual Studio]]></title><description><![CDATA[<div class="kg-card-markdown"><p><code>quicktype</code> is now available for Xcode, Visual Studio, and Visual Studio Code.</p>
<p>There are many ways to use <code>quicktype</code>; the <a href="https://app.quicktype.io">quicktype.io web app</a> is the most powerful UI, works offline, and doesn't send your data over the Internet so you can use it with any data, securely.</p>
<p>However, if</p></div>]]></description><link>https://blog.quicktype.io/quicktype-extensions/</link><guid isPermaLink="false">5a826bb3de887a0f41cbb2a3</guid><dc:creator><![CDATA[David]]></dc:creator><pubDate>Tue, 13 Feb 2018 04:57:53 GMT</pubDate><media:content url="https://blog.quicktype.io/content/images/2018/02/quicktype-xcode-copy.png" medium="image"/><content:encoded><![CDATA[<div class="kg-card-markdown"><img src="https://blog.quicktype.io/content/images/2018/02/quicktype-xcode-copy.png" alt="Paste JSON as code in Xcode and Visual Studio"><p><code>quicktype</code> is now available for Xcode, Visual Studio, and Visual Studio Code.</p>
<p>There are many ways to use <code>quicktype</code>; the <a href="https://app.quicktype.io">quicktype.io web app</a> is the most powerful UI, works offline, and doesn't send your data over the Internet so you can use it with any data, securely.</p>
<p>However, if you spend hours a day within your favorite editor or IDE, switching context to a web app feels sub-optimal. Thankfully, <code>quicktype</code> is now available in Xcode, Visual Studio, and Visual Studio Code, allowing you to instantly paste JSON as statically-typed models and marshaling code without switching apps.</p>
<p>With the <a href="https://itunes.apple.com/us/app/paste-json-as-code-quicktype/id1330801220?mt=12">Xcode extension</a>, you can paste JSON as Swift, Objective-C, C++, and Java:</p>
<p><img src="https://blog.quicktype.io/content/images/2018/02/app-store-2-copy.png" alt="Paste JSON as code in Xcode and Visual Studio"></p>
<p>The <a href="https://marketplace.visualstudio.com/items?itemName=quicktype.quicktype">VS Code extension</a>, is even more powerful, supporting all <code>quicktype</code> languages and allowing you to specify the top-level type name:</p>
<p><img src="https://blog.quicktype.io/content/images/2018/02/quicktype-vscode.png" alt="Paste JSON as code in Xcode and Visual Studio"></p>
<p>The <a href="https://marketplace.visualstudio.com/items?itemName=typeguard.quicktype-vs">Visual Studio extension</a> is much like the rest, allowing you to paste JSON as code without leaving VS:</p>
<p><img src="https://blog.quicktype.io/content/images/2018/02/vs-demo.gif" alt="Paste JSON as code in Xcode and Visual Studio"></p>
<p>James Montemagno wrote <a href="https://montemagno.com/paste-json-as-code-with-quicktype-io-in-visual-studio/">an in-depth overview</a>, including a comparison to Visual Studio's 'Paste JSON as Classes' feature.</p>
<p>All of these extensions are <a href="https://github.com/quicktype">open source on GitHub</a>, so check out how they're implemented and send a PR if you want to add a feature! We'd also love help building similar extensions for Atom, Sublime Text, and more—please <a href="http://slack.quicktype.io">join us on Slack</a> if you're interested in contributing.</p>
</div>]]></content:encoded></item><item><title><![CDATA[Little Big Detail #2: Contextual Class Names]]></title><description><![CDATA[<div class="kg-card-markdown"><p><a href="https://blog.quicktype.io/tag/little-big-details/">Little Big Details</a> are the subtle details that <a href="https://quicktype.io">quicktype</a> takes care of when turning your data into beautiful, readable code. This Little Big Detail is about how quicktype uses the names of outer types to generate nice alternate names when property type names collide.</p>
<p>In every programmer's life there comes</p></div>]]></description><link>https://blog.quicktype.io/little-big-detail-2-contextual-class-names/</link><guid isPermaLink="false">5a6764adde887a0f41cbb29e</guid><category><![CDATA[little-big-details]]></category><dc:creator><![CDATA[Mark]]></dc:creator><pubDate>Tue, 23 Jan 2018 16:39:25 GMT</pubDate><content:encoded><![CDATA[<div class="kg-card-markdown"><p><a href="https://blog.quicktype.io/tag/little-big-details/">Little Big Details</a> are the subtle details that <a href="https://quicktype.io">quicktype</a> takes care of when turning your data into beautiful, readable code. This Little Big Detail is about how quicktype uses the names of outer types to generate nice alternate names when property type names collide.</p>
<p>In every programmer's life there comes a day when they have to build a Swift app that stores data about celebrities and their pets.  The back-end might provide JSON data like:</p>
<pre><code class="language-json">{
    &quot;names&quot;: {
        &quot;given&quot;: &quot;Daenerys Targaryen&quot;,
        &quot;nick&quot;: &quot;Dany&quot;
    },
    &quot;job&quot;: &quot;Khaleesi&quot;,
    &quot;hobby&quot;: &quot;government&quot;,
    &quot;pet&quot;: {
        &quot;names&quot;: {
            &quot;given&quot;: &quot;Rhaegal&quot;,
            &quot;nick&quot;: &quot;Ray&quot;
        },
        &quot;species&quot;: &quot;dragon&quot;,
        &quot;size&quot;: &quot;huge&quot;
    }
}
</code></pre>
<br>
<p>Run quicktype on this data and it infers these types:</p>
<pre><code class="language-swift">struct Celebrity {
    let names: Names
    let job, hobby: String
    let pet: Pet
}

struct Names {
    let given, nick: String
}

struct Pet {
    let names: Names
    let species, size: String
}
</code></pre>
<br>
<p>Note that quicktype inferred that the <code>.names</code> and <code>.pet.names</code> properties have the same type, so it created only a single <code>Names</code> struct to represent both of them in the <code>Celebrity</code> and <code>Pet</code> structs.  Easy!</p>
<p>The Celebrity/Pet app was a hit, so now the programmer moves on to a real estate app, where they're confronted with data like:</p>
<pre><code class="language-json">{
    &quot;property&quot;: {
	    &quot;name&quot;: &quot;Blandings Castle&quot;,
        &quot;info&quot;: {
		    &quot;type&quot;: &quot;Castle&quot;,
		    &quot;county&quot;: &quot;Shropshire&quot;
        }
    },
    &quot;owner&quot;: {
	    &quot;name&quot;: &quot;Clarence Threepwood&quot;,
        &quot;info&quot;: {
		    &quot;job&quot;: &quot;Earl of Emsworth&quot;,
            &quot;arch-rival&quot;: &quot;Sir Gregory Parsloe-Parsloe&quot;
        }
    }
}
</code></pre>
<br>
<p>How should quicktype name the structs here?  The two outer ones, <code>Property</code> and <code>Owner</code>, are obvious, but each contains an <code>info</code> property with a distinct type.  If they had the same type, such as with <code>names</code> in the celebrity-pets app, quicktype would just name it <code>Info</code>, but the <code>info</code> properties have different types and therefore need different type names.</p>
<p>quicktype could take the easy route and name them <code>Info1</code> and <code>Info2</code>, or maybe <code>Info</code> and <code>OtherInfo</code>. Fortunately, quicktype is smarter than that and takes into account the outer types of the <code>info</code> properties, suggesting <code>PropertyInfo</code> for <code>Property.info</code> and <code>OwnerInfo</code> for <code>Owner.info</code>:</p>
<pre><code class="language-swift">struct RealEstate {
    let property: Property
    let owner: Owner
}

struct Owner {
    let name: String
    let info: OwnerInfo
}

struct OwnerInfo {
    let job, archRival: String
}

struct Property {
    let name: String
    let info: PropertyInfo
}

struct PropertyInfo {
    let type, county: String
}
</code></pre>
<br>
<p>Little Big Details like this are how quicktype generates code as you would have written it. Think quicktype is going a good job? <a target="_blank" href="https://twitter.com/intent/tweet?url=http%3A%2F%2Fblog.quicktype.io%2Flittle-big-detail-2-contextual-class-names%2F&via=quicktypeio&text=Amazing%21%20quicktype%20Little%20Big%20Detail%20%232%3A%20Contextual%20Class%20Names">Please share</a>!</p>
</div>]]></content:encoded></item><item><title><![CDATA[Little Big Detail #1: Perfect Property Names]]></title><description><![CDATA[This first Little Big Detail is part of how quicktype turns JSON property names into nice property names in your preferred target language.]]></description><link>https://blog.quicktype.io/little-big-detail-1-perfect-property-names/</link><guid isPermaLink="false">5a564611de887a0f41cbb290</guid><category><![CDATA[little-big-details]]></category><dc:creator><![CDATA[Mark]]></dc:creator><pubDate>Wed, 10 Jan 2018 17:02:38 GMT</pubDate><content:encoded><![CDATA[<div class="kg-card-markdown"><p>This post is the first in a series we’re calling “<a href="https://blog.quicktype.io/tag/little-big-details/">Little Big Details</a>”. It explains some of the subtle details that <a href="https://quicktype.io">quicktype</a> takes care of when turning your data into code, and the surprising amount of meticulous technical work behind these details. One of quicktype’s main goals is to generate the code that <em>you would have written</em>; the Little Big Details account for much of how quicktype achieves this.</p>
<p>The first Little Big Detail is about how quicktype turns JSON property names into nice property names in your preferred target language. Let's say you have some JSON like this:</p>
<pre><code class="language-json">{ &quot;my_favorite_url&quot;: &quot;https://quicktype.io/&quot; }
</code></pre>
<br>
<p>What should the property name corresponding to <code>&quot;my_favorite_url&quot;</code> be? If you write C#, the answer is <code>MyFavoriteUrl</code>.  <a href="https://golang.org">Gophers</a> prefer <code>MyFavoriteURL</code>, because they like their acronyms all caps, whereas in C++ you might just go with <code>my_favorite_url</code>.  In Java you have getter and setter methods rather than properties, so <code>my_favorite_url</code> becomes <code>getMyFavoriteURL</code> and <code>setMyFavoriteURL</code>:</p>
<pre><code class="language-csharp">// C# class for { &quot;my_favorite_url&quot;: &quot;...&quot; }
public class Demo
{
    public string MyFavoriteUrl { get; set; }
}
</code></pre>
<br>
<pre><code class="language-java">// Java class for { &quot;my_favorite_url&quot;: &quot;...&quot; }
public class Demo {
    private String myFavoriteURL;
    public String getMyFavoriteURL() { return myFavoriteURL; }
    public void setMyFavoriteURL(String value) { this.myFavoriteURL = value; }
}
</code></pre>
<br>
<pre><code class="language-swift">// Swift struct for { &quot;my_favorite_url&quot;: &quot;...&quot; }
struct Demo {
    let myFavoriteURL: String
}
</code></pre>
<br>
<p>No matter what language you’re using, quicktype will figure out the best names for each property, and it will do so whether the JSON property is <code>&quot;my_favorite_url&quot;</code>, <code>&quot;MyFavoriteURL&quot;</code>, or <code>&quot;my favorite URL!!?!?!&quot;</code>. How does quicktype do this?</p>
<p>First, quicktype <a href="https://github.com/quicktype/quicktype/issues/191">splits up the JSON property name</a> into its component words, in this example <code>my</code>, <code>favorite</code>, and <code>url</code>.  Then it figures out which words are acronyms using two rules:</p>
<ul>
<li>
<p>If the word is all caps, <em>and</em> the whole property name contains at least one lowercase letter, then treat the word as an acronym</p>
</li>
<li>
<p>If the word is in our <a href="https://github.com/quicktype/quicktype/blob/master/src/Acronyms.ts">big list of acronyms</a>, then it's an acronym</p>
</li>
</ul>
<p>The first rule will recognize acronyms in property names like <code>&quot;covered_by_ACA&quot;</code>, and the second one hopefully takes care of all the rest.</p>
<p>To put the words back together to form the target property name, each target language specifies whether a word should be lowercase, capitalized (e.g. <code>Url</code>), or all caps for each of four conditions:</p>
<ol>
<li>
<p>For the first word if it's not an acronym, like for <code>good</code> in <code>good_vibes</code></p>
</li>
<li>
<p>For any other word if it's not an acronym, such as for <code>three</code> and <code>musketeers</code> in <code>the_three_musketeers</code></p>
</li>
<li>
<p>For the first word if it's an acronym, like <code>json</code> in <code>json_property</code></p>
</li>
<li>
<p>For any other word if it's an acronym, like <code>url</code> in <code>homepage_url</code></p>
</li>
</ol>
<p>Target languages may also specify a separator (e.g. C++ uses an underscore) to place between words.</p>
<p>These mechanisms allow quicktype to express all property styles common among its target languages, so you get properties named according to your language’s preferred conventions, no matter how gnarly your JSON is! If you find a case that quicktype doesn't handle correctly, please <a href="https://github.com/quicktype/quicktype/issues">file an issue</a>, or <a href="http://slack.quicktype.io/">talk to us on Slack</a>.</p>
</div>]]></content:encoded></item><item><title><![CDATA[Typesafe GraphQL queries with quicktype]]></title><description><![CDATA[quicktype supports GraphQL now. Here we'll go over an example showing how to make type-safe GraphQL queries with quicktype.]]></description><link>https://blog.quicktype.io/graphql-with-quicktype/</link><guid isPermaLink="false">5a3f0c752b71e80f74b4d0b4</guid><category><![CDATA[graphql]]></category><category><![CDATA[how-to]]></category><dc:creator><![CDATA[Mark]]></dc:creator><pubDate>Fri, 22 Dec 2017 14:36:34 GMT</pubDate><content:encoded><![CDATA[<div class="kg-card-markdown"><p><a href="http://graphql.org">GraphQL</a> is the hot new API technology that the <a href="https://developer.github.com/v4/">cool kids</a> are talking about. Here’s how to use <code>quicktype</code> to easily generate typesafe code for GraphQL queries.</p>
<p><em>If you’d rather jump straight into sample code, please see <a href="https://github.com/quicktype/graphql-samples">the GraphQL sample repo</a>.</em></p>
<h3 id="whatisgraphqlandwhyisitcool">What is GraphQL and why is it cool?</h3>
<p>With traditional APIs, you usually have to make multiple queries to collect the data needed by your app. For example, to get the followers for all of a user’s GitHub repos, you’d first query for a list of the user’s repos, then perform a query for each repo to get the followers. For a user with <em>n</em> repos, that’s <em>n+1</em> queries, which means your app will be slow and will need a cumbersome UI (e.g. loading spinners, lazy lists).</p>
<p>With GraphQL, on the other hand, you specify exactly what information you want up front, so you get all the data your app needs in a <em>single</em> query.</p>
<p>Let's try it out by writing some queries against the GitHub API!  You can run these queries in your browser using <a href="https://developer.github.com/v4/explorer/">GitHub’s GraphiQL explorer</a>.  Here's a simple one for starters—it returns the current user's name and login info:</p>
<pre><code class="language-graphql">query {
  viewer {
    login
    name
  }
}
</code></pre>
<br>
<p>Here's the response I get for this query:</p>
<pre><code class="language-json">{
  &quot;data&quot;: {
    &quot;viewer&quot;: {
      &quot;login&quot;: &quot;schani&quot;,
      &quot;name&quot;: &quot;Mark Probst&quot;
    }
  }
}
</code></pre>
<br>
<p>Let's try a more complex query—suppose we want the names of my three most-starred repositories, including the number of stars for each:</p>
<pre><code class="language-graphql">query {
  viewer {
    login
    repositories(first: 3, orderBy: { field: STARGAZERS, direction: DESC }) {
      nodes {
        name
        stargazers {
          totalCount
        }
      }
    }
  }
}
</code></pre>
<br>
<p>The result of this GraphQL query is:</p>
<pre><code class="language-json">{
  &quot;data&quot;: {
    &quot;viewer&quot;: {
      &quot;login&quot;: &quot;schani&quot;,
      &quot;name&quot;: &quot;Mark Probst&quot;,
      &quot;repositories&quot;: {
        &quot;nodes&quot;: [
          { &quot;name&quot;: &quot;clojurec&quot;, &quot;stargazers&quot;: { &quot;totalCount&quot;: 845 } },
          { &quot;name&quot;: &quot;quicktype&quot;, &quot;stargazers&quot;: { &quot;totalCount&quot;: 256 } },
          { &quot;name&quot;: &quot;metapixel&quot;, &quot;stargazers&quot;: { &quot;totalCount&quot;: 70 } }
        ]
      }
    }
  }
}
</code></pre>
<br>
<p>The first thing to notice is that the structure of the JSON we get back depends on the query.  Unlike traditional APIs, which return a small, predefined set of types in response to queries, GraphQL APIs can return a huge permutation of types that are unique per query. For this reason, GraphQL API providers cannot provide strongly typed client libraries.</p>
<p>The second thing to notice is that the queries don’t specify types.  For example, the last query doesn't specify that <code>totalCount</code> is a number, so how do we know what type to use?  The answer lies in the GraphQL schema, which defines the types for all fields in all possible queries.  GraphQL servers allow clients to download this schema through an “introspection query”.</p>
<p>Let’s see how quicktype can download a GraphQL schema using an introspection query, then generate types and helper code for our GraphQL queries.</p>
<p>To send an introspection query (or any GraphQL query) to GitHub, you need an access token.  <a href="https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/">Follow these steps</a> to get one and save it in an environment variable:</p>
<pre><code class="language-bash">TOKEN=&lt;your token goes here&gt;
</code></pre>
<br>
<p>Make sure your token works by running this query on the command line:</p>
<pre><code class="language-bash">curl -H “Authorization: bearer $TOKEN” \
     -X POST -d '{ &quot;query&quot;: &quot;query { viewer { login }}&quot; }' \
     https://api.github.com/graphql
</code></pre>
<br>
<p>You should get back something like</p>
<pre><code class="language-json">{ &quot;data&quot;: { &quot;viewer&quot;: { &quot;login&quot;: &quot;schani&quot; } } }
</code></pre>
<br>
<p>Now you can ask quicktype to download the GraphQL schema from the GitHub API server:</p>
<pre><code class="language-bash">quicktype --graphql-server-header “Authorization: bearer $TOKEN” \
          --graphql-introspect https://api.github.com/graphql \
          --graphql-schema github.gqlschema
</code></pre>
<br>
<p>You should end up with a file named <code>github.gqlschema</code> that's a bit over 1MB.  Here’s a simplified excerpt from that file that describes the <code>totalCount</code> field::</p>
<pre><code class="language-json">{
    &quot;name&quot;: &quot;totalCount&quot;,
    &quot;description&quot;: &quot;Identifies the total count of items in the connection.&quot;,
    &quot;type&quot;: {
        &quot;kind&quot;: &quot;NON_NULL&quot;,
        &quot;ofType&quot;: {
            &quot;kind&quot;: &quot;SCALAR&quot;,
            &quot;name&quot;: &quot;Int&quot;,
        }
    }
}
</code></pre>
<br>
<p>Now that you have the GraphQL schema, save one of the queries from above to the file <code>query.graphql</code> and tell quicktype to generate types for you:</p>
<pre><code class="language-bash">quicktype --src-lang graphql --lang csharp \
          --graphql-schema github.gqlschema \
          query.graphql
</code></pre>
<br>
<p>I used the first query, which asked for my login and full name, and these are the C# types quicktype generated (if <code>csharp</code> isn’t your cup of tea, you can substitute <code>elm</code>, <code>swift</code>, <code>java</code>, <code>c++</code>, <code>go</code>, or <code>typescript</code> in the command line above):</p>
<pre><code class="language-csharp">public partial class Query
{
	[JsonProperty(&quot;viewer&quot;)]
	public User Viewer { get; set; }
}

public partial class User
{
	[JsonProperty(&quot;login&quot;)]
	public string Login { get; set; }

	[JsonProperty(&quot;name&quot;)]
	public string Name { get; set; }
}
</code></pre>
<br>
<p>quicktype generated C# classes that perfectly represent the type of the data returned by the query, adding <code>JsonProperty</code> annotations to ensure that the JSON is unmarshalled correctly. It also generated code to convert JSON to and from those nice types.</p>
<p>If you’d like to start using GraphQL right away, please check out our <a href="https://github.com/quicktype/graphql-samples">repository with sample code</a> which shows you how to do a complete GraphQL query from start to finish using quicktype in C# and TypeScript.</p>
</div>]]></content:encoded></item><item><title><![CDATA[quicktype news vol. 3]]></title><description><![CDATA[<div class="kg-card-markdown"><p>quicktype made radical progress in the last month: a drool-inducing new homepage, an eye-popping new app, jaw-dropping performance improvements, brain-melting GraphQL support, pricing, and more.</p>
<h2 id="adroolinducingnewhomepage">A drool-inducing new homepage</h2>
<p><img src="https://blog.quicktype.io/content/images/2017/12/homepage.png" alt="homepage"></p>
<p>Our <a href="https://quicktype.io/#hello">new homepage</a> gives an overview of quicktype’s capabilities, with links to important resources like our <a href="https://www.youtube.com/channel/UC0BAB7wFrlIhIpqV1RQPOgg">YouTube channel</a>, <a href="https://quicktype.us16.list-manage.com/subscribe/post?u=0229520b411dbc724ea268c8f&amp;id=e6201f9be3">mailing list</a></p></div>]]></description><link>https://blog.quicktype.io/quicktype-news-vol-3/</link><guid isPermaLink="false">5a3f0c752b71e80f74b4d0b3</guid><category><![CDATA[news]]></category><dc:creator><![CDATA[David]]></dc:creator><pubDate>Wed, 20 Dec 2017 23:23:26 GMT</pubDate><media:content url="https://blog.quicktype.io/content/images/2017/12/homepage-1.png" medium="image"/><content:encoded><![CDATA[<div class="kg-card-markdown"><img src="https://blog.quicktype.io/content/images/2017/12/homepage-1.png" alt="quicktype news vol. 3"><p>quicktype made radical progress in the last month: a drool-inducing new homepage, an eye-popping new app, jaw-dropping performance improvements, brain-melting GraphQL support, pricing, and more.</p>
<h2 id="adroolinducingnewhomepage">A drool-inducing new homepage</h2>
<p><img src="https://blog.quicktype.io/content/images/2017/12/homepage.png" alt="quicktype news vol. 3"></p>
<p>Our <a href="https://quicktype.io/#hello">new homepage</a> gives an overview of quicktype’s capabilities, with links to important resources like our <a href="https://www.youtube.com/channel/UC0BAB7wFrlIhIpqV1RQPOgg">YouTube channel</a>, <a href="https://quicktype.us16.list-manage.com/subscribe/post?u=0229520b411dbc724ea268c8f&amp;id=e6201f9be3">mailing list</a>, and <a href="https://github.com/quicktype/quicktype">GitHub repo</a>.</p>
<h2 id="aneyepoppingnewapp">An eye-popping new app</h2>
<p><img src="https://blog.quicktype.io/content/images/2017/12/mutli-sample-demo-2.png" alt="quicktype news vol. 3"></p>
<p>The quicktype web app now loads faster, and contains many new features and usability improvements:</p>
<ul>
<li>Ability to generate code for multiple samples. Check out <a href="https://app.quicktype.io/#s=music">the music sample</a> and notice that Artist is a top-level type, but is also contained within Album. quicktype infers this and generates the correct types.</li>
<li>JSON Schema input support. Generate code from JSON Schema, or generate JSON Schema from your samples, then feed the generated schema back into quicktype for full control over your output types.</li>
<li>A new JSON checker gives friendlier feedback for malformed JSON samples.</li>
<li>The ability to disable map and enum inference.</li>
<li>The ability to disable merging of similar classes.</li>
<li>Improved feedback on Copy.</li>
<li>Drag-and-drop support; try dragging one or many JSON files into quicktype!</li>
</ul>
<h2 id="brainmeltinggraphqlsupport">Brain-melting GraphQL support</h2>
<p>Unlike traditional APIs which return a small, predefined set of types in response to queries, GraphQL APIs return a huge permutation of types that are unique per query. For this reason, GraphQL API providers cannot provide strongly typed client libraries.</p>
<p>This is where quicktype shines–given a GraphQL schema and the GraphQL queries used in your app, quicktype will generate static types for the responses to these queries. You’ll get marshaling, type safety, and IDE autocompletion for GraphQL query responses with almost no effort:</p>
<pre><code class="language-bash">$ quicktype --lang csharp --src-lang graphql \
	--graphql-schema github.gqlschema github-sample-query.graphql
</code></pre>
<br>
<p>Stay tuned to <a href="http://blog.quicktype.io/">our blog</a>, where we’ll post more GraphQL details soon. In the meantime, you can check out <a href="https://github.com/quicktype/graphql-samples">this sample repo</a> which demonstrates how to use quicktype to generate code for the GitHub GraphQL API.</p>
<h2 id="brewinstallquicktype"><code>$ brew install quicktype</code></h2>
<p>macOS users who prefer to install developer tools with <a href="http://formulae.brew.sh/formula/quicktype">Homebrew</a> can now install quicktype with <code>brew install quicktype</code>.</p>
<h2 id="jawdroppingperformanceimprovements">Jaw-dropping performance improvements</h2>
<ul>
<li>We've ported the remaining PureScript implementation to TypeScript for simplicity and performance. quicktype is now easier to contribute to, and 100x faster on larger samples.</li>
<li>Type inference is faster thanks to a custom, compressed JSON representation.</li>
<li>Added enum support to TypeScript.</li>
<li>Simplified main module for easier use of quicktype as a library.</li>
</ul>
<h3 id="usingquicktypeasalibrary">Using quicktype as a library</h3>
<p>A simplified main module makes it much easier to use quicktype as a library. Here's an example of inferring the type of some JSON data, and outputting Swift code for parsing it:</p>
<pre><code class="language-js">import { quicktype } from &quot;quicktype&quot;;

quicktype({
  lang: &quot;swift&quot;,
  sources: [{
    name: &quot;Hipster&quot;,
    samples: ['{ &quot;name&quot;: &quot;Olivia&quot; }', '{ &quot;name&quot;: &quot;Gavin&quot; }']
  }]
}).then(result =&gt; {
  console.log(result.lines.join(&quot;\n&quot;));
});
</code></pre>
<br>
<p>You can find <a href="https://github.com/quicktype/quicktype/releases/tag/v7.0.0">this release</a> on GitHub.</p>
<h2 id="supportpricing">Support Pricing</h2>
<p><img src="https://blog.quicktype.io/content/images/2017/12/pricing.png" alt="quicktype news vol. 3"></p>
<p>We've released <a href="https://quicktype.io/#pricing">support pricing info</a> for using quicktype in production with confidence. We’re eager to know what you think of our pricing–is this what you would expect? What’s missing?</p>
<h2 id="werestillhavingacontest">We’re still having a contest</h2>
<p>We want to learn how people use quicktype, so we’re having a contest to see who can write the best blog post or make the best screencast showing it off. Explain how you use quicktype in your own projects, or demo an interesting use for quicktype that we haven't thought of yet. The best submissions will win one of the following:</p>
<ul>
<li><strong>Best Blog</strong>: $100 gift certificate or $200 donated to charity in your name.</li>
<li><strong>Best Screencast</strong>: $150 gift certificate or $300 donated to charity in your name.</li>
<li><mark><strong>Super Bonus</strong></mark>: Double your reward if your blog or screencast features a new target language that you implemented yourself!</li>
</ul>
<p>To enter the contest, simply publish a blog or screencast about quicktype and tweet it to <a href="https://twitter.com/quicktypeio">@quicktypeio</a> before <s>January</s> March 1, 2018. We’ll judge submissions on clarity, creativity, and technical merit.</p>
<hr>
<p>That's all for this edition of quicktype news. Please <a href="http://slack.quicktype.io/">say &quot;👋&quot; on Slack</a> if you'd like to get in touch with us. Thanks!</p>
</div>]]></content:encoded></item></channel></rss>