Home > Mobile >  How to convert a Json object with multiple objects in it (legacy) to a Json array
How to convert a Json object with multiple objects in it (legacy) to a Json array

Time:03-24

I have the following Json:

"elements": {
                "1": {
                  "label": "1fwef"
                },
                "2": {
                  "label": "2wefewfewf"
                },
                "3": {
                  "label": "wefwffe3"
                },
                "4": {
                  "label": 4
                },
                "5": {
                  "label": 5
                },
                "6": {
                  "label": 6
                },
                "7": {
                  "label": 7
                },
                "8": {
                  "label": 8
                },
                "9": {
                  "label": 9
                },
                "10": {
                  "label": 10
                }
              }
            }

I would need to deserialise or convert elements to Json array (elements is a little part of a big json response) because would be crucial iterate it in multiple cases. Keep in mind that the size of elements won't be always de same, it can be 1 or can be 40 or whatever. The values that contains each "NUMBER" field also can be different but that is ok, I just need to convert those "NUMBER" objects/fields to a list.

At the first time seemed to me easy but now I am struggling, maybe somebody can give some light :D, any help appreciated!!!

I have tried many ways to deserialise it: I have tried to leave it as an JsonObject and use it checking its components, but as I need to know how many objects are in elements to display different views (crucial business logic) I need it as an array.

CodePudding user response:

Here's how you can do it:

// Extract the elements object
val elementsObject = jsonObject.getJSONObject("elements")

// Get a list of all the keys 1...10 (in your case)
val listOfKeys = elementsObject.keys()

// Then iterate over the keys and get the label object
listOfKeys.forEach { key ->
   val labelObject = elementsObject.getJSONObject(key)
   val labelValue = labelObject.getString("label")

   print("$key:$labelValue") // 1:1fwef 2:2wefewfewf 3:wefwffe3 4:4 5:5 6:6 7:7 8:8 9:9 10:10 
}

CodePudding user response:

you can use gson type converters. first, add gson dependency.

implementation 'com.google.code.gson:gson:2.8.9'

Then, you can use the functions to convert objects to and from json. Example -


To json -

val jsonContent = Gson().toJson(content))

From json

val tempNotesJsonAsList = Gson().fromJson(i, mutableListOf<String>().javaClass)
  • Related