Values with different types Gson - Java

1

I'd like to know if there is a way with Gson to get values of different types in a "key-value" array in Json. Here's the example:

{
"events":[
            {"event":"comprou-produto",
             "timestamp":"2016-09-22T13:57:32.2311892-03:00",
             "custom_data":[
                    {"key":"product_name","value":"Camisa Azul"},
                    {"key":"transaction_id","value":"3029384"},
                    {"key":"product_price","value":100}]} ... outros elementos]}

In this example we have the array "custom_data" with the key-value fields, and notice that "product_price" is a field and its value is a double (or int if you prefer), the others being Strings. How can I get these values with Gson. I made a class to try to read this dataset. Following:

public class Event {

private final String event;
private final String timestamp;
private final double revenue;
private final List<CustomData> custom_data;

//Constructor.
public Event(String event, String timestamp, double revenue, List<CustomData> custom_data) {
    this.event = event;
    this.timestamp = timestamp;
    this.revenue = revenue;
    this.custom_data = custom_data;
}

//nested class.
public static class CustomData{

    private final String key;
    private final String value;

    public CustomData(String key, String value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public String getValue() {
        return value;
    }
}

Note: The revenue field refers to extra information about the set of events that the outermost array has, in some cases like the one in the example I simply ignore it. Thank you.

    
asked by anonymous 06.10.2018 / 19:44

1 answer

1

You can use a Map for this.

public class Event {
    ...
    private final List<Map<String, Object>> custom_data;
    ...
}

Parse:

EventWrapper events = new Gson().fromJson(jsonData,EventWrapper.class);

EventWrapper.java

public class EventWrapper {
    private Event[] events;

    public Event[] getEvents() {
        return events;
    }
}

Access:

for (Map<String, Object> customData : event.getCustom_data()) {
    String chave = (String) customData.get("key");
    String valor = String.valueOf(customData.get("value"));
    System.out.println(String.format("%s => %s", chave, valor));
}

Result:

Parse: EventWrapper events = new Gson (). FromJson (jsonData, EventWrapper.class);

    
06.10.2018 / 20:52