0

I have this following json file

    {"Abra":[
    "Bangued",
    "Boliney",
    "Bucay",
    "Bucloc",
    "Daguioman",
    "Danglas"],

    "Agusan del Norte":[
    "Buenavista",
    "Butuan City",
    "Cabadbaran City",
    "Carmen",
    "Jabonga",
    "Kitcharao"]
    }

they represents municipalities in my country and inside them are the city they covered. My problem is that I don't know how to parse them in my code. The Municipalities are not static because it depends on the sender on whatever municipality he/she wants to send. Can anybody help me on what I should do.. I've been looking for solution all over the web but I did not find any success. thank you in advance.

2 Answers 2

1

What you can do is converting this JSONObject into a JSONArray instead, such as following:

[
    "Abra":[
    "Bangued",
    "Boliney",
    "Bucay",
    "Bucloc",
    "Daguioman",
    "Danglas"],

    "Agusan del Norte":[
    "Buenavista",
    "Butuan City",
    "Cabadbaran City",
    "Carmen",
    "Jabonga",
    "Kitcharao"]
]

Then you can use the method get() of JSONArray allowing you to get the element at the specified position.

However the content of each element seems not to ne a valid JSON as it looks like an enum.

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

3 Comments

Thank you for your answer, I already tried what you have stated, however I get an error indicating Unterminated array at character 8 Maybe its because the elements are not valid JSON.. as what you have said.. I really don't have an idea what's a valid json or not.. so thank you.. I will study on Json more and use another way in solving this problem.
A valid Json needs a key + its value. Here what you have looks like an enum ( see here spacetelescope.github.io/understanding-json-schema/reference/… ). If you can, the best solution is to reformatting your json.
I agree, I guess I just have to give up on this format.. thank you.. i will take a look at your reference
1

keys() will return an iterator for the names in the JSON object. It can be used to cycle through the keys and retrieve the corresponding array.

JSONObject json = new JSONObject("");
Iterator<String> iterator = json.keys();
while(iterator.hasNext()){
    String key = iterator.next();
    JSONArray array = json.getJSONArray(key);
}

2 Comments

Thank you for your answer, I tried this immediately after I read your answer however I encountered this error Unterminated array at character 8 ..
If you have some problem with your json formatting, you could run it through a json validator. The json that you posted is valid, so I assume you're not using that.

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.