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.
You used the Gson API to get this data ? I’m in doubt just how to do this action with Gson.
– Matheus Vinícius de Andrade
I edited the answer with how I did the conversion
– lcrmj