杰克逊Json到POJO映射
问题描述:
杰克逊第一次入门,我有问题与Java类映射JSON数据。该JSON结构如下:杰克逊Json到POJO映射
{
"status": "ok",
"all_tags": [
{
"id": 14,
"term_name": "Term 1",
"category_details": [
{
"category_ID": 21,
"category_name": "Category Name",
"category_count": 1,
"category_image": "...202x300.jpg"
},
{
"category_ID": 19,
"category_name": "Category Sample",
"category_count": 3,
"category_image": "...202x300.jpg"
}
]
},
{
"id": 17,
"term_name": "Term 2",
"category_details": [
{
"category_ID": 20,
"category_name": "Category Sample Again",
"category_count": 1,
"category_image": "....200x300.jpg"
}
]
},
.......
]
}
我以前Jsonschema2pojo网站产生CategoryDetail.java,AllTag.java,Response.java POJO类。
因为我访问JSON在线我用凌空提出要求:
mRequestQueue = JacksonNetwork.newRequestQueue(getApplicationContext());
mRequestQueue.add(new JacksonRequest<AllTag>(Request.Method.GET,
"http://example.com/file.json",
new JacksonRequestListener<AllTag>() {
@Override
public void onResponse(AllTag response, int statusCode, VolleyError error) {
if (response != null) {
// I am not sure how to parse the JSON
// and map the data to POJO
} else {
Log.e(TAG, "An error occurred while parsing the data! Stack trace follows:");
error.printStackTrace();
}
}
@Override
public JavaType getReturnType() {
return SimpleType.construct(AllTag.class);
}
})
);
我读了documentation,但我不知道如何将JSON数据映射到类,所以我可以循环和retreive数据后来。真的很感谢杰克逊知识的人带我走向正确的方向。
答
您需要杰克逊阅读snakecase,也多了一个类效应初探
public class Response {
String status;
List<AllTags> allTags;
//setter getter
// constructor
}
更新请求
mRequestQueue = JacksonNetwork.newRequestQueue(getApplicationContext());
mRequestQueue.add(new JacksonRequest<Response>(Request.Method.GET,
"http://example.com/file.json",
new JacksonRequestListener<Response>() {
@Override
public void onResponse(Response response, int statusCode, VolleyError error) {
if (response != null) {
// response.getAllTags() loop here
// I am not sure how to parse the JSON
// and map the data to POJO
} else {
Log.e(TAG, "An error occurred while parsing the data! Stack trace follows:");
error.printStackTrace();
}
}
@Override
public JavaType getReturnType() {
return SimpleType.construct(Response.class);
}
})
);
感谢您的评论中,我使用[此扩展名(https://开头的github .com/spothero/volley-jackson-extension),所以我不认为我需要一个响应类? –
您需要一个完全代表您的json对象的类结构。查看https://github.com/spothero/volley-jackson-extension/blob/master/Demo/VolleyJacksonDemo/src/main/java/com/spothero/volleyjacksondemo/DateReturnType.java和http://date.jsontest。 com /供参考在排列杰克逊分机响应 – Shashank
提供,所以我在问题中发布的类结构是不正确的?我遵循同一个例子,但这个例子非常简单,并不包括如何存储对象数组。 –