你会发现它其实很简单,我推荐Jackson 2,它有很多很好的文档并且被广泛使用。
作为您示例的基本用法,我创建了一个 Java POJO 来将您的响应示例映射到它。
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Response {
private Map<String, Object> response;
@JsonProperty("current_observation")
private Map<String, Object> currentObservation;
public Map<String, Object> getResponse() {
return response;
}
public void setResponse(Map<String, Object> response) {
this.response = response;
}
public Map<String, Object> getCurrentObservation() {
return currentObservation;
}
public void setCurrentObservation(Map<String, Object> currentObservation) {
this.currentObservation = currentObservation;
}
}
然后是一个测试类来测试您的响应并将其绑定到 POJO。
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
String responseString = "{\n" +
"\"response\": {\n" +
"\"version\": \"0.1\",\n" +
"\"termsofService\": \"http://www.wunderground.com/weather/api/d/terms.html\",\n" +
"\"features\": {\n" +
"\"conditions\": 1\n" +
"}\n" +
"},\n" +
"\"current_observation\": {\n" +
"\"image\": {\n" +
"\"url\": \"http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png\",\n" +
"\"title\": \"Weather Underground\",\n" +
"\"link\": \"http://www.wunderground.com\"\n" +
"},\n" +
"\"display_location\": {\n" +
"\"full\": \"San Francisco, CA\",\n" +
"\"city\": \"San Francisco\",\n" +
"\"state\": \"CA\",\n" +
"\"state_name\": \"California\",\n" +
"\"country\": \"US\",\n" +
"\"country_iso3166\": \"US\",\n" +
"\"zip\": \"94101\",\n" +
"\"latitude\": \"37.77500916\",\n" +
"\"longitude\": \"-122.41825867\",\n" +
"\"elevation\": \"47.00000000\"\n" +
"}\n" +
"}\n" +
"}";
try {
Response response = objectMapper.readValue(responseString, Response.class);
System.out.print("Output: "+ response.getResponse().get("termsofService"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
从示例响应中打印 termsOfService 的 main 方法的输出:
Output: http://www.wunderground.com/weather/api/d/terms.html
希望对你有帮助,
何塞·路易斯