I am trying to serialize my below JSON to a DataMetrics
class -
String json = "[{\"min\": 0,\"max\": 1209,\"avg\": 1.9203402,\"count\": 7344636,\"sumSq\": 71832774, \"stddev\": 2.4683187, \"median\": 2,\"percentileMap\": {\"95\": 4},\"metricName\": \"TransactionDuration\",\"dimensions\": {\"env\": \"dev\",\"pool\": \"titan\",\"Name\": \"Client::Sync\", \"Type\": \"Client::Sync\"},\"value\": 14104200}]";
Generally, for nested objects like dimensions
you'll declare another POJO for it
class DataMetrics {
private String metricName;
private Map<String, Integer> percentileMap;
private String median;
private String stddev;
private String sumSq;
private String count;
private String avg;
private String max;
private String min;
private Dimensions dimensions;
private class Dimensions{
private String env;
private String pool;
private String Name;
}
}
And below is the code I have which works fine -
public void test() {
String json = "[{\"min\": 0,\"max\": 1209,\"avg\": 1.9203402,\"count\": 7344636,\"sumSq\": 71832774, \"stddev\": 2.4683187, \"median\": 2,\"percentileMap\": {\"95\": 4},\"metricName\": \"TransactionDuration\",\"dimensions\": {\"env\": \"dev\",\"pool\": \"titan\",\"Name\": \"Client::Sync\", \"Type\": \"Client::Sync\"},\"value\": 14104200}]";
final Gson gson = new Gson();
final Type type = new TypeToken<List<DataMetrics>>() {}.getType();
final List<DataMetrics> records = gson.fromJson(json, type);
}
Here member variable names is matching the JSON property name exactly as it is.
stdDev
=> stddev
name
=> Name
percentile
=> percentileMap
Now Is there any way, I can have my own variable names and map the JSON property name to those names, if possible? I don't want to keep Name
as a variable name in my Dimensions class.
Use SerializedName
annotation:
import com.google.gson.annotations.SerializedName;
class DataMetrics {
[..]
private Dimensions dimensions;
private class Dimensions{
private String env;
private String pool;
@SerializedName("Name")
private String nameYouWant;
}
}
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.