Values with different types Gson - Java

Asked

Viewed 96 times

1

I wonder, if there is a way with Gson to get values of different types in a "key-value" array in Json. Follow 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 above we have the "custom_data" array with the key-value fields, and note that "product_price" is a field and its value is a double (or int if you prefer), the rest being Strings. How can I get these values with Gson. I made a class to try to read this data set. Follow:

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 field Revenue, refers to extra information of the set of events that the most external array has, in some cases like the example I simply ignore it.
Thank you.

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));
}

Upshot: Screenshot das variaveis no debugger

Parse: Eventwrapper Events = new Gson(). fromJson(jsonData,Eventwrapper.class);

  • You used the Gson API to get this data ? I’m in doubt just how to do this action with Gson.

  • I edited the answer with how I did the conversion

Browser other questions tagged

You are not signed in. Login or sign up in order to post.