0

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

1
  • 1
    Is that json even valid? Commented Mar 22, 2021 at 2:27

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

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.