4

I've a JSONArray and I need to get the hashmap with the values, because I need to populate a stream, like twitter done. What you suggest to do?

1
  • Oh, yeah, I forgott. Sorry :) Commented Nov 29, 2010 at 19:45

2 Answers 2

11
HashMap<String, String> pairs = new HashMap<String, String>();
for (int i = 0; i < myArray.length(); i++) {
   JSONObject j = myArray.optJSONObject(i);
   Iterator it = j.keys();
   while (it.hasNext()) {
      String n = it.next();
      pairs.put(n, j.getString(n));
   }
}

Something like that.

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

2 Comments

Thanks! This worked for my situation. Only edit would be to replace the pairs.add... with pairs.put....
I would like to suggest to define the "String n,JSONObject j,Iterator it" out side of the for loop.Because if we have to deal with large number of JSONObjects ,the Stack will get overflow and the program may get slower.
0

You can use Iterator for getting JsonArrays. or use this way

eg. json

{
........
........

 "FARE":[   //JSON Array
    {
    "REG_ID":3,
    "PACKAGE_ID":1,
    "MODEL_ID":9,
    "MIN_HOUR":0
    .......
    .......
    .......
    }
      ]
}
HashMap<String, String> mMap= new HashMap<>();
for (int i = 0; i < myArray.length(); i++) {

   JSONObject j = myArray.optJSONObject(i);
    mMap.put("KEY1", j.getString("REG_ID"));
    mMap.put("KEY2", j.getString("PACKAGE_ID"));
    ............
    ............
}

note: For better coding use Iterator

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.