Parse json with variable key

I just came up with a complicated problem.

Below is the json answer where the key is a variable (GUID)

How can I take it apart? I tried google gson but that didn't work.

{ "87329751-7493-7329-uh83-739823748596": { "type": "work", "status": "online", "icon": "landline", "number": 102, "display_number": "+999999999" } } 
+4
source share
2 answers

If you use Gson, you can create a custom class to represent your JSON data to parse your response, and then you can use 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 pseudocode):

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

Then parse your JSON response with Map , for example:

 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 Map , for example:

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

Note. If you want to get only the GUID value, you do not need to create the YourClass class, and you can use the same parsing code, but using a common object in Map , i.e. Map<String, Object> .

+8
source

I assume that you are looking for a way to get a GUID. You can try the Object.keys function.

 json_string = '{"87329751-7493-7329-uh83-739823748596":{"type":"work","status":"online","icon":"landline","number":102,"display_number":"+999999999"}}'; object = JSON.parse(js); key = Object.keys(object)[0]; alert(key); 

It worked on firefox 21.0, but I can not guarantee that it will work in every browser.

0
source

Source: https://habr.com/ru/post/1484138/


All Articles