Home > database >  Parse nested Map in Kotlin
Parse nested Map in Kotlin

Time:03-11

I´m having a problem with parsing - what I think is- a Kotlin Map. A SDK gives me some data by making a jsonStruct and then a val latestData = data.jsonStruct.fieldsMap out of it. When I print the latestData.toString() I get this (changed values and made it simpler for showing purposes): Edit: it´s a google protobuf

{id=string_value: "id1"
  , data=struct_value {
   fields {
     key: "key1"
     value {
       list_value {
         values {
           string_value: "v1"
         }
         values {
           string_value: "v2"
         }
       }
     }
   }
   fields {
     key: "key17"
     value {
       struct_value {
         fields {
           key: "id2"
           value {
             string_value: "value2"
           }
         }
         fields {
           key: "id3"
           value {
             struct_value {
               fields {
                 key: "key2"
                 value {
                   string_value: "info"
                 }
               }
             }
           }
         }
       }
     }
   }
 }
 , someID=string_value: "someID"
}

How can I e.g. save "v2" or "info" into variables? The "id1" can be saved with latestData["id"], but I couldn´t figure out how to do it for the rest since it´s nested. Thanks.

CodePudding user response:

I'd suggest parsing the JSON with the klaxon library.

If that doesn't answer you question, you could try to use gson to convert it to a Java object

CodePudding user response:

works like this:

val myValue = latestData["data"]!!.structValue.fieldsMap["key17"]!!.structValue.fieldsMap["id2"]!!.stringValue
  • Related