Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse json with variable key

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"
  }
}
like image 253
DroidEngineer Avatar asked Jun 03 '13 06:06

DroidEngineer


People also ask

How do you parse a JSON to a variable in Python?

Example 1: Read and print a JSON file in JSON format Create a python file named json1.py with the following script. JSON module is used to read any JSON data using python script. open() method is used to read student. json file and load() method is used to store the data into the variable, data.

Can a key be a number in JSON?

JSON only allows key names to be strings. Those strings can consist of numerical values.

Can JSON have multiple keys?

There can be multiple key-value pairs. Two key-value pairs must be separated by a comma (,) symbol. No comments (// or /* */) are allowed in JSON data.


1 Answers

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>.

like image 135
MikO Avatar answered Oct 10 '22 11:10

MikO