我第一次使用Gson库。我正在发出HTTP请求并提取响应(JSON响应)并需要提取特定结果。
StringBuilder response;
try (BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream()))) {
String line;
response = new StringBuilder();
while((line = in.readLine()) != null) {
response.append(line);
}
}
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();
System.out.println(gson.toJson(response));
响应如下所示,我只需要提取cardBackId
:
[{\"cardBackId\":\"0\",\"name\":\"Classic\",\"description\":\"The only card back you\u0027ll ever need.\",\"source\":\"startup\",\"sourceDescription\":\"Default\",\"enabled\":true,\"img\":\"http://wow.zamimg.com/images/hearthstone/backs/original/Card_Back_Default.png\",\"imgAnimated\":\"http://wow.zamimg.com/images/hearthstone/backs/animated/Card_Back_Default.gif\",\"sortCategory\":\"1\",\"sortOrder\":\"1\",\"locale\":\"enUS\"
答案 0 :(得分:1)
您可以使用JSONPath(用于选择JSON对象部分的Java库)从字符串中提取所需的部分。
或者,您可以编写一个仅包含所需字段的类:
public class CardBackIdResponse {
public int cardBackId;
}
然后使用Gson将JSON解组到您的对象中:
CardBackIdResponse[] cardBackIdResponses = gson.fromJson(response.toString(), CardBackIdResponse[].class);
System.out.println("cardBackId = " + cardBackIdResponses[0].cardBackId);
当从JSON解组对象时,如果Gson无法在对象中找到用JSON中的值填充的字段,它将只丢弃该值。这就是我们可以在这里使用的原则。
修改:根据this SO question更改上面的答案以处理JSON数组。