9

I just came up with challenging problem.

Below is json response where key is variable (a GUID)

How can I parse it? I've tried Google Gson, but that didn't work.

{
  "87329751-7493-7329-uh83-739823748596": {
    "type": "work",
    "status": "online",
    "icon": "landline",
    "number": 102,
    "display_number": "+999999999"
  }
}
5
  • 1
    Not sure I fully understand the question. That JSON is valid according to JSONLint, so you should be able to parse it as JSON. Commented Jun 3, 2013 at 6:44
  • agreed. But problem is randonly generated GUID. Commented Jun 3, 2013 at 6:45
  • I've create pojo against it but its doesn't work because each time GUID generated on server side is different and unique.:) Commented Jun 3, 2013 at 6:46
  • 1
    Have you tried: Object.keys(obj) Commented Jun 3, 2013 at 6:47
  • Just parse the JSON into maps and arrays and access the stuff the old-fashioned way. You don't have to create custom classes for everything -- most other languages don't do that, and it's meaningless extra work for a simple JSON structure in many cases. Commented Jun 3, 2013 at 11:10

1 Answer 1

14

If you use Gson, in order to parse your response you can create a custom class representing your JSON data, and then you can use a Map.

Note that a Map<String, SomeObject> is exactly what your JSON represents, since you have an object, containing a pair of string and some object:

{ "someString": {...} }

So, first your class containing the JSON data (in pseudo-code):

class YourClass
  String type
  String status
  String icon
  int number
  String display_number

Then parse your JSON response using a Map, like this:

Gson gson = new Gson();
Type type = new TypeToken<Map<String, YourClass>>() {}.getType();
Map<String, YourClass> map = gson.fromJson(jsonString, type);

Now you can access all the values using your Map, for example:

String GUID = map.keySet().get(0);
String type = map.get(GUID).getType();

Note: if you only want to get the GUID value, you don't need to create a class YourClass, and you can use the same parsing code, but using a generic Object in the Map, i.e., Map<String, Object>.

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.