16

I want to parse my Json array dynamically. and want to get array of KEYS for each element under jsonarray. i an getting this through iterator. but not getting the sequeance as per the output json formate.

my JSON Formate :

{
  "result": "Success",
  "AlertDetails": [
    {
      "ShipmentNumber": "SHP34",
      "Customer": "BEST",
      "DateCreated": "2012-08-29T04:59:18Z"
      "CustomerName": "BEST"
    },
    {
      "ShipmentNumber": "SHP22",
      "Customer": "BEST",
      "DateCreated": "2012-08-29T05:34:18Z"
      "CustomerName": "Jelly"
    }
  ]
}

here is My Code :

    JSONArray array = jsonobject.getJSONArray("AlertDetails");

    JSONObject keyarray = array.getJSONObject(0);
    Iterator temp = keyarray.keys();
        while (temp.hasNext()) {
                    String curentkey = (String) temp.next();
                    KEYS.add(curentkey);

    }
Log.d("Parsing Json class", "  ---- KEYS---- " + KEYS);

What i am getting in logcate output:

 ---- KEYS---- [DateCreated,CustomerName, Customer, ShipmentNumber]

What i want :

 ---- KEYS---- [ShipmentNumber, Customer, DateCreated,CustomerName]
6
  • @LazyNinja no it's just a name. Commented Aug 29, 2012 at 12:36
  • @LazyNinja Yes it is an arraylist. can you please help me to get out of this? would be great if you give me suggestions for this issue. Commented Aug 29, 2012 at 13:55
  • 1
    Dont anybody told you that JSON object doesnt follow any specific ordering...the both output is equall as per the json format...now the question is why u want that in that particular format?? Commented Aug 31, 2012 at 13:06
  • @MKJParekh:thnx for your Support. but i want to Display each KEY Name in my Screen as Column Name in same Formate that i am getting it From the WS Response. the KEYS are Not known to me in Advance. Commented Aug 31, 2012 at 13:21
  • Then add one more thing in your WS Response..a JSON object with key name with value as their index ID 1, NAME 2 DATE 3..so so... and decide upon that... Commented Aug 31, 2012 at 13:25

5 Answers 5

12
+50

The JSONObject documentation (link: http://developer.android.com/reference/org/json/JSONObject.html) has the following description for the keys() function:

public Iterator keys ()

Since: API Level 1

Returns an iterator of the String names in this object. The returned iterator supports remove, which will remove the corresponding mapping from this object. If this object is modified after the iterator is returned, the iterator's behavior is undefined. The order of the keys is undefined.

So you may get the keys but the order is undefined. You may use any of the sorting algorithms if you want the keys in any particular order.

EDIT

Since you are unaware of the order of KEYS you are getting from the WS, after receiving the data you may show the details on screen in an ordered format . After building the arraylist KEYS, you may sort it alphabetically using the following:

Collections.sort(KEYS);  

This will order the Strings in the KEYS arraylist according to its natural ordering (which is alphabetically).

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

1 Comment

Thnx for your Support. can you suggest me any of the Algorithm to solve this problem and that can give me the Arraylist that has same KEYS order that i am getting in Response from WS?
6

I just come to know when I press ctlr+space bar, in which its clearly written that behavior of the keys is undefined, orders is not maintain by keys.

enter image description here

Arun George said@ correctly that you have to use any sorting method to achieve your goal.

and for sorting may be this link will help you.

Comments

6

Use GSON library from google. It has a a lot of setting to read/create/parse json array and json objects. I didn't test it to find the solution, but I think it's very simple and full featured tool and can solve the problem.

Comments

4

Use different library to parse json dynamically.

Below I wrote a piece of code based on Jackson JSON Processor, which is the best JSON library in my opinion

public void test() throws IOException {
    String str = "{\n" +
            "  \"result\": \"Success\",\n" +
            "  \"AlertDetails\": [\n" +
            "    {\n" +
            "      \"ShipmentNumber\": \"SHP34\",\n" +
            "      \"Customer\": \"BEST\",\n" +
            "      \"DateCreated\": \"2012-08-29T04:59:18Z\",\n" +
            "      \"CustomerName\": \"BEST\"\n" +
            "    }\n" +
            "  ]\n" +
            "}";

    JsonFactory factory = new JsonFactory();
    JsonParser jsonParser = factory.createJsonParser(str);

    JsonToken jsonToken;
    SerializedString alertDetails = new SerializedString("AlertDetails");
    while (!jsonParser.nextFieldName(alertDetails)) { /* move to AlertDetails field */ }

    jsonParser.nextToken(); // skip [ start array
    jsonParser.nextToken(); // skip { start object
    // until } end object
    while ((jsonToken = jsonParser.nextToken()) != JsonToken.END_OBJECT) {
        if (jsonToken == JsonToken.FIELD_NAME) {
            System.out.println(jsonParser.getCurrentName());
        }
    }

}

It simply prints out field names in the same order as in json:

ShipmentNumber
Customer
DateCreated
CustomerName

EDIT

Naturally you can use other libraries like gson etc. But remember, as is written on json.org, that:

An object is an unordered set of name/value pairs.

and the order of keys depends on implementation and might vary in each request.

Comments

3

There is also the method names();

Returns an array containing the string names in this object.

Edit: returns names in undefined order. Suggestions: parse it on your own

2 Comments

yes you are right.i have also tried it but that is also giving me same Undefined order of KEYS that i am getting with using key() Method. would be very great full if you have any More Suggestion to solve it out this issues.
Then I would suggest that you parse it on your own

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.