Fastest way to parse big json android

Posted by jem88 on Programmers See other posts from Programmers or by jem88
Published on 2014-06-07T13:06:16Z Indexed on 2014/06/07 15:38 UTC
Read the original article Hit count: 252

Filed under:
|

I've a doubt that doesn't let me sleep! :D I'm currently working with big json files, with many levels. I parse these object using the 'default' android way, so I read the response with a ByteArrayOutputStream, get a string and create a JSONObject from the string. All fine here. Now, I've to parse the content of the json to get the objects of my interest, and I really can't find a better way that parse it manually, like this:

        String status = jsonObject.getString("status");
    Boolean isLogged = jsonObject.getBoolean("is_logged");

    ArrayList<Genre> genresList = new ArrayList<Genre>();

    // Get jsonObject with genres
    JSONObject jObjGenres = jsonObject.getJSONObject("genres");
    // Instantiate an iterator on jsonObject keys
    Iterator<?> keys = jObjGenres.keys();

    // Iterate on keys
    while( keys.hasNext() ) {
        String key = (String) keys.next();

        JSONObject jObjGenre = jObjGenres.getJSONObject(key);
        // Create genre object
        Genre genre = new Genre(
                jObjGenre.getInt("id_genre"),
                jObjGenre.getString("string"),
                jObjGenre.getString("icon")
        );

        genresList.add(genre);
    }

    // Get languages list
    JSONObject jObjLanguages = jsonObject.getJSONObject("languages");
    Iterator jLangKey = jObjLanguages.keys();
    List<Language> langList = new ArrayList<Language>();
    while (jLangKey.hasNext()) {
        // Iterate on jlangKey obj
        String key = (String) jLangKey.next();
        JSONObject jCurrentLang = (JSONObject) jObjLanguages.get(key);

        Language lang = new Language(
                jCurrentLang.getString("id_lang"),
                jCurrentLang.getString("name"),
                jCurrentLang.getString("code"),
                jCurrentLang.getString("active").equals("1")
        );
        langList.add(lang);
    }

I think this is really ugly, frustrating, timewaster, and fragile. I've seen parser like json-smart and Gson... but seems difficult to parse a json with many levels, and get the objects! But I guess that must be a better way... Any idea? Every suggestion will be really appreciated. Thanks in advance!

© Programmers or respective owner

Related posts about android

Related posts about JSON