https://kotlinlang.org logo
m

MR3Y

07/26/2022, 9:02 PM
Is it possible to deserialize only a fragment of the Json response?. For example, if I have a Json response like this:
Copy code
{
  "responseHeader": {
    "a": 0,
    "b": 407,
    "c": {
         ....
    }
  },
  "response": {
    "numFound": 2,
    "start": 0,
    "docs": [
      {
        "foo": "foo",
        "bar": "bar"
      },
      {
        "foo": "foo",
        "bar": "bar"
      }
    ]
  },
  "unimportant": {
    "unimportant": []
  }
}
I'm interested only in the
response
part, so, Instead of deserializing the entire response, I want to just deserialize this part. is this possible with kotlinx.serialization? Of course I can deserialize the whole response & get rid of the irrelevant parts on the client side, but this would be a waste of time. So, it would be nice if there is a built-in way to do this.
e

ephemient

07/26/2022, 9:09 PM
you can define a model that only contains
response
, and as long as you use
Json { ignoreUnknownKeys = true }
having a partial model is fine
it's always going to be necessary for the JSON parser to scan through
responseHeader
if it comes first, though. at a minimum it needs to match up quotes and brackets
m

MR3Y

07/26/2022, 10:46 PM
@ephemient this is exactly what I'm doing currently (
partial model + ignoreUnknownKeys
) but I'm getting
JsonDecodingException
, this is why I asked the question in the first place, because I thought there is a hidden feature somewhere for that. but yeah, I guess you're right about JSON parser need to scan through
responseHeader
and brackets first
2 Views