【发布时间】:2014-09-16 05:50:31
【问题描述】:
我收到来自第三方网络服务的低于 json 响应。
{
"Values":[
{
"Date":"2013-08-01",
"Value":1451674.0
},
{
"Date":"2013-09-01",
"Value":1535645.0
},
{
"Date":"2013-10-01",
"Value":1628753.0
},
{
"Date":"2013-11-01",
"Value":1279856.0
},
{
"Date":"2013-12-01",
"Value":1471991.0
},
{
"Date":"2014-01-01",
"Value":1571008.0
},
{
"Date":"2014-02-01",
"Value":1863232.0
},
{
"Date":"2014-03-01",
"Value":2126469.0
},
{
"Date":"2014-04-01",
"Value":2146069.0
},
{
"Date":"2014-05-01",
"Value":2735564.0
},
{
"Date":"2014-06-01",
"Value":1977808.0
},
{
"Date":"2014-07-01",
"Value":1932503.0
}
]
}
现在应该是什么 pojo 属性以及如何用 pojo 映射它?
class Value{
@JsonProperty("Values")
List<DateValuePair> values;
//setter getter
}
class DateValuePair{
@JsonProperty("Date")
String date;
@JsonProperty("Value")
String value;
//setter getter
}
//映射
Value visits = new Value();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
mapper.configure(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, true);
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://api.8df1fc");
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
mapper.readValue(line, Value.class);
}
遇到以下异常:
{"Values":[{"Date":"2013-08-01","Value":1451674.0},{"Date":"2013-09-01","Value":1535645.0},{"Date":"2013-10-01","Value":1628753.0},{"Date":"2013-11-01","Value":1279856.0},{"Date":"2013-12-01","Value":1471991.0},{"Date":"2014-01-01","Value":1571008.0},{"Date":"2014-02-01","Value":1863232.0},{"Date":"2014-03-01","Value":2126469.0},{"Date":"2014-04-01","Value":2146069.0},{"Date":"2014-05-01","Value":2735564.0},{"Date":"2014-06-01","Value":1977808.0},{"Date":"2014-07-01","Value":1932503.0}]}
Exception in thread "main" org.codehaus.jackson.map.JsonMappingException: Root name 'Values' does not match expected ('Value') for type [simple type, class com.domain.Value]
at [Source: java.io.StringReader@e9a398d; line: 1, column: 2]
谢谢!
【问题讨论】:
-
更多细节,你试过什么代码,使用什么库,什么是pojo类???
-
Wundwin 建议正确!请尝试
-
我试过 Vihar .. 效果很好.. 非常感谢您的帮助。
标签: java json web-services rest jackson