引入包
org.apache.httpcomponents:httpclient:4.5.13
com.google.code.gson:gson:2.9.0
JSON类型
import java.util.List;
public class ResultBean {
public String status;
public String state;
public List<Value> data;
public static class Value {
public String value;
}
}
测试用例
import com.google.gson.*;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
int total = 0;
// HTTP请求数据
CloseableHttpClient client = HttpClients.createDefault();
RequestBuilder requestBuilder = RequestBuilder.get()
.setUri("http://test/test.json");
// .addParameter("page", "" + 1)
// .addParameter("sign", "1")
// .addParameter("t", "" + 1);
HttpUriRequest httpUriRequest = requestBuilder.build();
HttpResponse httpResponse = client.execute(httpUriRequest);
String jsonString = EntityUtils.toString(httpResponse.getEntity());
System.out.println(jsonString);
// Gson解析json
Gson gson = new Gson();
// json转换成ResultBean对象
ResultBean resultBean = gson.fromJson(jsonString, ResultBean.class);
for (ResultBean.Value v : resultBean.data) {
total += Integer.parseInt(v.value.trim());
}
System.out.println("Total:" + total);
// 遍历JSON
JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
JsonArray jsonArray = (JsonArray) jsonObject.get("data");
for(JsonElement jsonElement : jsonArray) {
JsonObject jo = jsonElement.getAsJsonObject();
System.out.println(jo.get("value"));
}
}
}
运行结果
{
"status": "success",
"state": "1",
"data": [{
"value": 1
}, {
"value": 2
}
]
}
Total:3
1
2