1

I want to parse a JSON file using native Android org.json.

The JSON is complex, and does not have a pre-defined structure. It can contain several levels of nesting for a key and just one value for another key. I can define any number of key value pairs with any type of structure.

I need to convert this to a dictionary. I cannot use any third party libraries like Jackson or Gson (for reasons I don't wish to discuss here). I do understand that it can be done very easily using the public APIs provided by these libraries.

If I want to do this on my own (using org.json perhaps), what is the best way to do it? Do I need to read every value, check if it is a JSONArray/JSONObject or a value and then perform recursion? Or can I just read the map that is in the JSONObject class using reflection and use it?

Any help is appreciated. Thanks!

1 Answer 1

1

Here is a snippet to get you started:

Iterator<?> keys = jsonData.keys();
while( keys.hasNext() ){
     String key = (String)keys.next();
     String value =  jsonData.getString(key);
}

You will need to check if the data is an object or an array, here is how you do it:

if (item instanceof JSONArray)
{
    JSONArray jsonArray = (JSONArray) item;
}
else
{
    JSONObject jsonObject = (JSONObject) item;
}

then use recursion to parse nested objects.

Good luck!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.