杰克逊杰森到POJO的映射

时间:2016-11-05 17:13:25

标签: java android arrays jackson android-volley

第一次使用Jackson,我遇到了使用java类映射JSON数据的问题。 JSON结构如下:

{
  "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.javaAllTag.javaResponse.java POJO课程。

因为我在线访问JSON,所以我使用了volley来提出请求:

        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数据映射到类,所以我可以稍后循环和检索数据。真的很感激有杰克逊知识的人能把我带到正确的方向。

1 个答案:

答案 0 :(得分:0)

你需要杰克逊阅读蛇蝎以及另外一个类别的回应

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);
        }
    })
 ); 
相关问题