4

I have a response coming from a web service, data is in JSON form.

JSONObject event:-

{
  "15:00":{"type":1,"status":null,"appointment_id":null}, 
  "16:00":{"type":1,"status":null,"appointment_id":null},
  "17:00":{"type":1,"status":null,"appointment_id":null},
  "18:00":{"type":1,"status":"1","appointment_id":5}
}

I don't know the key values, they are random. So when i iterate the data using iterator by fetching keys and hasNext(). It returns the data but changes the order of coming data.

Iterator AppoinmentIter = event.keys();
while(AppoinmentIter.hasNext()){   
        String appointmentTime = (String)AppoinmentIter.next();   
        JSONObject appointmentDetails = event.getJSONObject(appointmentTime);
 }

I want the data in exact order in which it is coming. I checked this link, it suggests to use LinkedHashMap. But here they are inserting the value by keys. And i don't know the keys in my data. So how can i iterate the data in correct order. Please help..

Community
  • 1
  • 1
Vikas Gupta
  • 1,530
  • 5
  • 21
  • 34
  • What's the name of your returned JSONObject? You should be able to loop through the index of that Object/Array and extract the structure that contains your key/value mapping without using an Iterator. What is event? A JSONObject, a JSONArray? – Jade Byfield Jul 08 '13 at 05:41
  • @JadeByfield event is a json object it contains the data shown in question. – Vikas Gupta Jul 08 '13 at 05:43
  • did you see this for gson http://code.google.com/p/json-simple/wiki/DecodingExamples#Example_4_-_Container_factory ? – Saurabh Jul 08 '13 at 05:43
  • You probably don't have any control over the server, but IMHO it was not a good idea for someone to design a protocol using JSON where the order of the keys matter. Are you _sure_ you need the keys in a specific order? IMHO the protocol should have been designed with an array of arrays, then. – Ray Toal Jul 08 '13 at 05:44
  • Key is in your data is variable for '15:00' ... – Pankaj Kumar Jul 08 '13 at 05:43
  • I has been already asked here http://stackoverflow.com/questions/3948206/json-order-mixed-up . – sandrstar Jul 08 '13 at 05:45
  • @PankajKumar yes that's the key, i know that, but it won't be same each time so i have to iterate data according to that – Vikas Gupta Jul 08 '13 at 05:46

3 Answers3

2

That's not how JSON works. It assumes order doesn't matter unless you have an array. If you want order to matter, you're using the wrong format- you need yo use an array of times->values rather than just times->value.

For your particular application, you can get the set of keys, then sort them with a custom comparator that uses the value parsed as a time to order them. But the built in libraries won't do it for you, because you aren't using JSON as its designed.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • I know that but i can not change the data pattern as its not in my hand :( – Vikas Gupta Jul 08 '13 at 05:54
  • Then you'll need to get the list of all keys, sort them yourself, then go through the sorted list. The reason it won't work otherwise is that the JSONObject uses a HashMap as its internal data structure, the order is lost. – Gabe Sechan Jul 08 '13 at 05:56
  • I lost you here, if i'll store the value in a list and then i sort that list. then i can get the data in sort order or not ? – Vikas Gupta Jul 08 '13 at 06:01
1

Vikas, as far as i understood your problem i managed to retrieve json object in expected format, hope this will help you. Enjoy!!

   String s = "{ \"15:00\":{\"type\":1,\"status\":null,\"appointment_id\":null},\"16:00\":{\"type\":1,\"status\":null,\"appointment_id\":null},\"17:00\":{\"type\":1,\"status\":null,\"appointment_id\":null},\"18:00\":{\"type\":1,\"status\":\"1\",\"appointment_id\":5}}";
    try {
        JSONObject jobj = new JSONObject(s);
        Iterator iter = jobj.keys();
        while(iter.hasNext()){   
            String appointmentTime = String.valueOf(iter.next());
            aRRaY.add(appointmentTime);

     }
      Collections.sort(aRRaY); 
      for(String key : aRRaY){
          JSONObject appointmentDetails = jobj.getJSONObject(key);
          System.out.println(key +" ----- "+appointmentDetails);
      }

    }
    catch (JSONException e) {
        e.printStackTrace();
    }
Ravi K. Sharma
  • 545
  • 8
  • 15
0

I don't know the implementation you have done, and what 3pp you involved. But anyway, try below codes, you would get what you want.

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map.Entry;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class Test {

    private static final ObjectMapper mapper = new ObjectMapper();

    public static void main(String[] args) {
        String json = "{"
                + "\"15:00\":{\"type\":1,\"status\":null,\"appointment_id\":null}, "
                + "\"16:00\":{\"type\":1,\"status\":null,\"appointment_id\":null},"
                + "\"17:00\":{\"type\":1,\"status\":null,\"appointment_id\":null},"
                + "\"18:00\":{\"type\":1,\"status\":\"1\",\"appointment_id\":5}"
            + "}";
        LinkedHashMap<String, LinkedHashMap<String, Integer>> fromJSON = fromJSON(
            json, LinkedHashMap.class);
        for (Entry<String, LinkedHashMap<String, Integer>> entry : fromJSON
            .entrySet()) {
            System.out.print(entry.getKey());
            System.out
                .println(" || status = " + entry.getValue().get("status"));
        }
    }

    public static <T> T fromJSON(String input, Class<T> clazz) {
        try {
            return mapper.readValue(input != null ? input : "null", clazz);
        } catch (JsonParseException e) {
            throw new RuntimeException(e);
        } catch (JsonMappingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
Howard
  • 4,474
  • 6
  • 29
  • 42
  • The key point is using LinkedHashMap as internal data structure in JSONObject, rather than HashMap. – Howard Jul 08 '13 at 06:06