0

i want to Grouping Gson response to new model in kotlin. I have existing json like this:

{
  "content": {
    "data": [
      {
        "Group": "Data 1",
        "Message": "HDKSSHSI"
      },
      {
        "Group": "Data 1",
        "Message": "EIEENC"
      },
      {
        "Group": "Data 2",
        "Message": "CBOXDLX"
      },
      {
        "Group": "Data 3",
        "Message": "6999d"
      },
      {
        "Group": "Data 3",
        "Message": "DKDD"
      }
    ]
  }
}

with gson model:

  data class MyModel(
  @SerializedName("content" ) var content : Content? = Content()
)

data class Content (
  @SerializedName("data" ) var data : ArrayList<Data> = arrayListOf()
)

data class Data (
  @SerializedName("Group"   ) var Group   : String? = null,
  @SerializedName("Message" ) var Message : String? = null
)

Now I want to grouping with new model, and looks new json format like this:

{
  "content": {
    "data": [
      {
        "Group": "Data 1",
        "Message": [
          "HDKSSHSI",
          "EIEENC"
        ]
      },
      {
        "Group": "Data 2",
        "Message": [
          "CBOXDLX"
        ]
      },
      {
        "Group": "Data 3",
        "Message": [
          "6999d",
          "DKDD"
        ]
      }
    ]
  }
}

with new model gson

data class ExampleJson2KtKotlin (
  @SerializedName("content" ) var content : Content? = Content()
)
data class Content (
  @SerializedName("data" ) var data : ArrayList<Data> = arrayListOf()
)
data class Data (
  @SerializedName("Group"   ) var Group   : String?           = null,
  @SerializedName("Message" ) var Message : ArrayList<String> = arrayListOf()
)

so how to make it? thanks. sorry for my english

Amay Diam
  • 2,561
  • 7
  • 33
  • 57
  • Add the code to show the API call you are making to get the JSON and what you are doing there. – tomerpacific Aug 25 '22 at 12:20
  • This needs just basic List/Map manipulation, see https://kotlinlang.org/docs/collection-grouping.html – pdem Aug 25 '22 at 13:33
  • Could you please clarify what you want to achieve? Are you looking for code which supports both the old and the new JSON format at the same time (in that case [this question](https://stackoverflow.com/q/46568964) and similar ones might help)? Are you looking for conversion from the old JSON format to the new JSON format? – Marcono1234 Aug 25 '22 at 23:19

1 Answers1

0

use @JsonAdapter annotation override write and read

litao
  • 304
  • 3
  • 4