简体   繁体   中英

Unable to parse json array using jackson json streaming

I am unable to parse below JSON stream that contains an array of object, here I have added just one object for simplification.

{
"status": true,
"categories": [
    {
        "obj_cat_id": "26",
        "session_user": "212233379",
        "timestamp": "2011-10-30 04:34:53"
    }
]

}

What I tried :

try {
        JsonFactory f = new JsonFactory();
        JsonParser jp = f.createJsonParser(is);
        jp.nextToken(); /* START_OBJECT */

        while (jp.nextToken() != JsonToken.END_OBJECT) {

            if ("status".equals(jp.getCurrentName())) {
                jp.nextToken(); /* VALUE_TRUE */
                status = jp.getText();
                Constants.showLog("Status", jp.getText());
            } else if ("categories".equals(jp.getCurrentName())) {

                //jp.nextToken();
                while (jp.nextToken() != JsonToken.END_ARRAY) {
                    //jp.nextToken();

                    while (jp.nextToken() != JsonToken.END_OBJECT) {

                        String namefieldOne = jp.getText();
                        Constants.showLog(TAG, namefieldOne);
                    }

                }

            } 
        }
        jp.close();

The major issue is that when I do jp.nextToken where the current token is START_ARRAY it goes directly to END_ARRAY and I am not able to access its object values.

I am using Jackson Streaming parser for better efficiency.

Did you consider using GSON ? You can use it server-side or client-side (Android). Saving shared preferences as JSON and stuff :)

public class Category {
       Long obj_cat_id;
       Long session_user;
       Timestamp timestamp;

       /* Getters && Setters */
}

public class MyEntity
{
        private boolean status;
        private List<Category> categories;

        /* Getters && Setters */
}

public class Serializer
{ 
    private static Gson _gson;

    static
    {
        _gson = new Gson();
    }

    public static <T> T jsonToObject(String json, Type type)
    {
        return _gson.fromJson(json, type);
    }

    public static <T> String getJson(T object)
    {
        Type type = new TypeToken<T>()
        {}.getType();
        return _gson.toJson(object, type);
    }
}

Using like this:

String myJsonString = "{
"status": true,
"categories": [
    {
        "obj_cat_id": "26",
        "session_user": "212233379",
        "timestamp": "2011-10-30 04:34:53"
    }
]
}";

MyEntity myEntity= Serializer.jsonToObject(myJsonString , MyEntity.class);
/* And vice-versa */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM