下面是我通過從服務API調用回來的JSON字符串。爲了理解目的,我只用了三個reportRecords
來縮短它。一般情況下,它可能有5〜50 reportRecords
如何迭代JSON數組並使用GSON從中提取每個JSON對象?
{
"aggRecords": {
"reportRecords": [
{
"min": 0,
"max": 12,
"avg": 0.3699187,
"count": 246,
"sumSq": 571,
"stddev": 1.4779372,
"median": 0,
"percentileMap": {
"95": 4
},
"metricName": "TransactionDuration",
"dimensions": {
"env": "dev",
"pool": "titan",
"Name": "PostProcessing",
"Type": "PostProcessing"
},
"value": 91
},
{
"min": 0,
"max": 23,
"avg": 2.3991289E-4,
"count": 1463031,
"sumSq": 3071,
"stddev": 0.045814946,
"median": 0,
"percentileMap": {
"95": 0
},
"metricName": "TransactionDuration",
"dimensions": {
"env": "dev",
"pool": "titan",
"Name": "ResourceContext",
"Type": "ResourceContext"
},
"value": 351
},
{
"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
}
]
},
"minRecordsMap": {}
}
現在從上面的JSON響應,我需要提取reportRecords
其Name
是Client::Sync
。意思是,我只需要從上面的JSON響應中提取低於reportRecords
。
現在我需要爲Client::Sync
上述reportRecords
解析以下對象 -
public class DataMetrics {
private String pool;
private String name;
private String type;
private String env;
private String metricName;
private String percentile;
private String median;
private String stdDev;
private String sumSq;
private String count;
private String avg;
private String max;
private String min;
// getters and setters here
}
以上變量,映射這樣的 -
pool is titan
name is Client::Sync
type is Client::Sync
env is dev
metricNname is TransactionDuration
95th percentile is 4
median is 2
stdDev is 2.4683187
sumSq is 71832774
count is 7344636
avg is 1.9203402
max is 1209
min is 0
我使用GSON庫這裏下面是我到目前爲止所嘗試的 -
private static RestTemplate restTemplate = new RestTemplate();
public static void main(String[] args) {
String jsonLine = restTemplate.getForObject("some_url", String.class);
System.out.println(jsonLine); // here jsonLine will give me above big JSON String
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("aggRecords");
JsonArray jarray = jobject.getAsJsonArray("reportRecords");
// now how do I iterate JsonArray and get each JSON object
// and then check "name" property of each object, if "Client::Sync" found, read that object for all properties
// and set it using setters.
}
現在我無法理解如何迭代JsonArray並從中提取每個JSON對象?
@hexin我正在GSON和我想上面的例子不使用GSON。 – john
對不起,我的失敗:/ – hexin