简体   繁体   中英

Wrong deserializing List<Object> with gson

I debug CUSTOMER object with List<Object> inside:

在此处输入图像描述

This is CUSTOMER.class:

   public class CUSTOMER { 
    
 @XmlElements({
        @XmlElement(name = "ADDRESS", type = ADDRESS.class),
        @XmlElement(name = "ZIP", type = ZIP.class),
        @XmlElement(name = "CITY", type = CITY.class),
        @XmlElement(name = "COUNTRY", type = COUNTRY.class),
    })
    protected List<Object> addressAndZIPAndCITY;
    
    // other fields
    }

But when I deserialize and create json from it, it contains only:

{
"addressAndZIPAndCITY": [
      {
        "value": "some value",
        "type": "some type"
      },
      {
        "value": "some value 2",
        "type": "some type 2"
      }]
}

The ADRESS, ZIP, CITY and COUNTRY objects titles are missing. So it's bad deserialized.

I can't change List<Object> declaration. Is there option to deserialize it as json with ADRESS, ZIP, CITY etc.? Like this:

{
    "addressAndZIPAndCITY": [{
            "ADDRESS": {
                "value": "some value",
                "type": "some type"
            }
        }, {
            "ZIP": {
                "value": "some value 2",
                "type": "some type 2"
            }
        }
    ]
}

EDIT: I mean it looks like GSON doesn't know which object is there, but may be you know how to add some annotations or something else to the model to recognize it?

I think you either have to write a custom serializer for CUSTOMER or you create another class from which you do the serialization:

public class GsonCustomer {
    private List<Map<String, Object>> addressAndZipAndCity = new ArrayList<>();
    // other fields
    public GsonCustomer(CUSTOMER customer) {
        for (Object o: customer.getAddressAndZipAndCity()) {
            Map<String, Object> map = new HashMap<>();
            map.put(o.getClass().getSimpleName(), o);
            addressAndZipAndCity.add(map);
        }
        // copy other fields
    }
}

// so you can do: gson.toJson(new GsonCustomer(customer))

Or as mentioned:

public class CustomerAdapter implements JsonSerializer<CUSTOMER> {

    @Override
    public JsonElement serialize(CUSTOMER customer, Type type, JsonSerializationContext jsonSerializationContext) {
        // TODO
    }
}

// Gson gson = new GsonBuilder().registerTypeAdapter(CustomerAdapter.class, new CustomerAdapter()).create();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM