title: Gson or Moshi: field in POJO could have 2 types, how to save to any of the fields
body: <p>EDITED:</p>
  
  <p>Here is the json string that I have:</p>
  
  <pre><code>json#1
  {
      [
          {
              field1 : ""
              field2 : 0
              field3 : "Amount not fixed" or field : 250 // this field can be string or int
          },
          {
              field1 : ""
              field2 : 0
              field3 : "Amount not fixed" or field : 250 // this field can be string or int
          }
  
      ]
  }
  
  json#2
  {
      field1 : ""
      field2 : 0
      field3 : "Amount not fixed" or field : 250 // this field can be string or int
  }
  </code></pre>
  
  <p>OR it could any json string from server. The point here is there could be 1 or more fields that may have a dynamic value (is this case field3 can be a string or int)</p>
  
  <p>Then I want to deserialize them to any POJO</p>
  
  <pre><code>class Temp1 {
      // field1 here
      // field2 here
  
      @SerializedName("field3")
      val field3Int: Int? = null
  
      @SerializedName("field3")
      val field3String: String? = null
  
  }
  </code></pre>
  
  <p>It means if the value sent from server is an <code>Int</code>, I want to set the value to <code>field3Int</code>. If it is a <code>String</code>, set to <code>field3String</code>.</p>
  
  <p>There could be other POJO that will have these kind of fields that may have dynamic value.</p>
  
  <p>Thanks to Serj to his answer but I still cant make it work on the TypeAdapter class after I edited the question to show my real situation.</p>
  
  <p>Btw. I use this with Retrofit2 like this:</p>
  
  <pre><code>val moshi = Moshi.Builder()
                      .add(MultitypeJsonAdapterAdapter())
                      .build()
              return Retrofit.Builder().baseUrl(baseUrl)
  
                      .addConverterFactory(MoshiConverterFactory.create(moshi))
                      .client(httpClient.build())
                      .build()
  </code></pre>