testovtest
testovtest

Reputation: 171

Android. How to parse JsonArrays inside JsonArray

I use retrofit and json. I need to parse a json like that:

{
"outer_array": [
"one" : [{}, {}],
"two" : [{}],
"three" : [{}],
....
]
}

Here is part of my code:

@SerializedName("outer_array") var data: List<List<Data>>

But how can I parse each element of the "outer_array" array by key. Arrays inside "outer_array" can be from 0 to n. Maybe I should use a TypeAdapter. But I don't know how to apply it for this case, please help me

Upvotes: 0

Views: 73

Answers (2)

Amin
Amin

Reputation: 3186

The JSON you've provided is not valid. You can check it on JSONLint. I guess it should be either an array (without "one" :) or an object ([ in front of outer_array should be {) in the first case your code is fine and in second case you can use a Map (like HashMap) and if you need to convert that map to array you can use something like this

data class MyClass(
    @SerializedName("outer_array") var data: HashMap<String, List<Data>>
){
    val dataAsArray get() = data.map{ it.value }
}

But if you have to parse this invalid data (e.g you cannot ask the provider/backend to fix this) even a TypeAdapter cannot help, because the JSON is invalid and you'll face an exception, you can use a regex to replace invalid [ ] with { } (but this is so dumb, try to convince the backend dev to fix the json :D)

Upvotes: 2

Nicola Revelant
Nicola Revelant

Reputation: 102

I suggest you to use Gson, a Google service to parse JSON strings into Objects and viceversa. Simple add "implementation 'com.google.code.gson:gson:2.8.6'" into dependencies in the app's Gradle file in your Android project.

You could use two methods: toJson(Object obj) and fromJson(string json, Class<>) if you have a class called 'MyObject', you have to put as second parameter of 'fromJson': MyObject.class, or MyObject[].class if an array.

GitHub: https://github.com/google/gson

Upvotes: 1

Related Questions