title: Gson - nice serialisation of Kotlin enums with a value
body: <p>I have an enum with values</p>
  
  <pre><code>enum class Foo(val serverVal:Int) {
       BAR(1),
       BUG(2)
  }
  </code></pre>
  
  <p>that I would like to use with a class:</p>
  
  <pre><code>data class C1(val fooVal:Foo)
  </code></pre>
  
  <p>I want to be able to serialise it with a code that looks as close as can be to:</p>
  
  <pre><code>Gson().toJson(C1(Foo.BAR))
  </code></pre>
  
  <p>That would yield</p>
  
  <pre><code>{"fooVal":1}
  </code></pre>
  
  <p>Instead of the default conversion, which is, of course <code>{"fooVal":"BAR"}</code>. If it was a string value I could have used <code>@SerializedName</code>, but I can't because it's an Int, not a String.</p>
  
  <p>Is there a simple way to add something to Foo, in order to show Gson how to take the Int value from Foo entries rather than their name?</p>
  
  <p>Examples I saw in Java include EnumAdapterFactory and TypeAdapter which are quite cumbersome and defeat the purpose of a pretty code.</p>
  
  <p>I would love to get a solution that is maintained inside the data structure.</p>
  
  <pre><code>enum class SomeEnum(val i:Int) {
     V1(1), V2(10), V3(5);
  
  companion object {
     @SerializeMeLikeThis
     fun toJson() = i;
  
     @DeserializeMeLikeThat
     fun fromJson(v:Int) = values().find{it.i == v}?:whatever
  }
  }
  </code></pre>
  
  <p>An ugly way but still encapsulated-ish</p>
  
  <pre><code>data class C2(@SerializedName("foo") var serverFoo:Int) {
      // Becomes a nightmare with many params.
      constructor(f:Foo) : this(F.serverVal)
      var foo:Foo 
        get() = Foo.values().find{serverFoo == it.serverVal}?:whatever
        set(v) { serverFoo = v.serverVal }
  }
  </code></pre>
  
  <p>So it can be called</p>
  
  <pre><code>Gson().toJson(C2(BAR))
  </code></pre>
  
  <p>and</p>
  
  <pre><code>// Result: Foo.BAR
  Gson().fromJson("""{"foo":"1"}""", C2::class.java).foo
  </code></pre>
  
  <p>Well, you can live on it...but it... :-(</p>
  
  <p>Any nice way?</p>
  
  <p>Thanks</p>