1

on IOS i have a code for parsing nested json. This json can contains string and object. It looks like this(Swift):

struct Place: Codable {
    let value: [Dependent]?
}

enum Dependent: Codable {
  case object(Place)
  case string(String)

  init(from decoder: Decoder) throws {
        let container =  try decoder.singleValueContainer()
        do {
            let objectVal = try container.decode(Place.self)
            self = .object(objectVal)
        } catch DecodingError.typeMismatch {
            let stringVal = try container.decode(String.self)
            self = .string(stringVal)
        }
    }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch self {
        case .object(let value):
            try container.encode(value)
        case .string(let value):
            try container.encode(value)
        }
    }
}

But its to hard understand how i can create the same parser for Kotlin, i did code like this:

data class Place(
    val value: List<Dependent>
)

sealed class Dependent {
    data class OBJECT(val value: Place): Dependent()
    data class STRING(val value: String): Dependent()
}

It doesnt work, i feel i missed something

UPD: The josn looks like this:

{
   "value": [
      "123123123",
      {"value": ["123123", "123123", {"value":["123"]}, "123"]}
    ]
}
4
  • 1
    Does this answer your question? Kotlin - Serialize JSON Array to multiple classes Commented Mar 3, 2022 at 12:01
  • 1
    can you put your json here . Commented Mar 3, 2022 at 12:37
  • @Mohmmaed-Amleh have added Commented Mar 3, 2022 at 13:02
  • @IvoBeckers im not sure Commented Mar 3, 2022 at 13:02

0

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.