title: Serialize flats objects of Java pojo to structured/nested json using Gson or Retrofit
body: <p>I have a Java class with fields annotated (dot separated) with expected JSON field names and I want to serialize this to nested JSON using Gson or retrofit convertors.</p>
  <p>note: Deserialization is not required.</p>
  <p><strong>Java Class</strong></p>
  <pre><code>public class InputData {
      public String type = &quot;Usage&quot;;
      public String timeframe = &quot;custom&quot;;
  
      @SerializedName(&quot;timePeriod.from&quot;)
      public String from = &quot;2022-07-14T00:00:00+00:00&quot;;
  
      @SerializedName(&quot;timePeriod.to&quot;)
      public String to = &quot;2022-07-26T23:59:59+00:00&quot;;
  }
  </code></pre>
  <p><strong>Expected JSON</strong></p>
  <pre><code>{
      &quot;type&quot;: &quot;Usage&quot;,
      &quot;timeframe&quot;: &quot;custom&quot;,
      &quot;timePeriod&quot; {
          &quot;from&quot;: &quot;2022-07-14T00:00:00+00:00&quot;,
          &quot;to&quot;: &quot;2022-07-26T23:59:59+00:00&quot;
      }
  }
  </code></pre>
  <p>I have tried a custom serializer but could convert primitive types to objects in JSON.</p>
  <p>I have been attempting TypeAdapterFactory to parse the annotations but there I could not read the value of the fields</p>
  <p>Any help would be much appreciated!</p>
  <p>I have a function which converts to HashMap from given field name and value</p>
  <pre><code>private static HashMap&lt;String, Object&gt; convertToObj(String key, String value) {
          HashMap&lt;String, Object&gt; root = new HashMap&lt;&gt;();
          Map&lt;String, Object&gt; m = root;
          String[] parts = key.split(&quot;\\.&quot;);
          for (int i = 0; i &lt; parts.length; i++) {
              String part = parts[i];
              if (i == parts.length - 1) {
                  // At last part so put value
                  m.put(part, value);
              } else {
                  // Before last part so put map
                  Map&lt;String, Object&gt; mm = (Map&lt;String, Object&gt;) m.get(part);
                  if (mm == null) {
                      mm = new HashMap&lt;&gt;();
                      m.put(part, mm);
                  }
                  m = mm;
              }
          }
          return root;
      }
  </code></pre>