Flatten icon indicating copy to clipboard operation
Flatten copied to clipboard

Two child attributes from same parent Gson Exception

Open robertoestivill opened this issue 9 years ago • 2 comments

Hello there,

I'm experiencing an issue with the following structure:

Json

{ 
 "coord":  {
    "lat": 32.123,
    "lon": 32,123
  }
}

Pojo

package com.example;

import com.google.gson.annotations.SerializedName;
import ru.noties.flatten.Flatten;
import ru.noties.flatten.Flattened;

public class Clazz{

  @Flatten("lat")
  @SerializedName("coord")
  public Flattened<Double> latitude;

  @Flatten("lon")
  @SerializedName("coord")
  public Flattened<Double> longitude;
}

Exception

Caused by: java.lang.IllegalArgumentException: class com.example.Clazz declares multiple JSON fields named coord
E/AndroidRuntime( 6497):    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:166)
E/AndroidRuntime( 6497):    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:96)
E/AndroidRuntime( 6497):    at com.google.gson.Gson.getAdapter(Gson.java:416)

I'm basically trying to avoid having two classes, one per Json object (root & coord)

Any clue what might be going on? Does this means that I can not flatten two child attributes from the same parent? Does this have anything to do with the fact that 'lat' and 'lon' are first inner attributes and therefore theres no really a chain in the @Flatten annotation ?

robertoestivill avatar Apr 15 '16 18:04 robertoestivill

Hi! Yeah, man, looks like one cannot flatten json like this... Gson throws an exception, because having duplicated keys is invalid... Right now I cannot see a way out

noties avatar Apr 27 '16 10:04 noties

@robertoestivill I have some different implementation. Probably not very effective, but it works with such attributes

Tishka17 avatar Jun 05 '16 13:06 Tishka17