2

I do have a json:

{
   "items":[
      {
         "id":"0000301553526",
         "values":{
            "name":{
               "value":{
                  "en_En":"Item"
               },
               "formatted":{
                 
               },
               "attribute":{
                  "group":{
                     "code":null,
                     "label":null
                  },
                  "group_mod":{
                     "code":null,
                     "label":null
                  },
                  "localizable":true,
                  "type":"text",
                  "code":"name",
                  "label":"name",
                  "visible":false,
                  "display_order":null
               }
            },
            "additonal_data":{
               "value":"",
               "attribute":{
                  "group":{
                     "code":null,
                     "label":null
                  },
                  "group_mod":{
                     "code":null,
                     "label":null
                  },
                  "localizable":true,
                  "type":"local",
                  "code":"ABCC",
                  "label":"action",
                  "visible":false,
                  "display_order":null
               }
            }
         }
      }
   ]
}

In object additonal_data value can be null or String, but sometimes I receive an array from backend. What is the correct approach to ignore wrong type of data and paste/set this property to null. Code I currently have related to issue:

class IgnoreDataAdapter<T> private constructor(
    private val delegate: JsonAdapter<T>
) : JsonAdapter<T>() {

    @FromJson
    override fun fromJson(reader: JsonReader): T? {
        reader.setFailOnUnknown(false)
        val peeked = reader.peekJson()
        val result: T? = try {
            delegate.fromJson(peeked)
        } catch (e: JsonDataException) {
            null
        } finally {
            peeked.close()
        }
        reader.skipValue()
        return result
    }

    @ToJson
    override fun toJson(writer: JsonWriter, value: T?) {
        delegate.toJson(writer, value)
    }
}

But in this case Object. I am interested in specific property to be set to null (when data are garbage). How could I achieve that (without parsing all property by property)?

Unii
  • 1,587
  • 15
  • 33
  • In this case, I don't think you have to buffer the whole value, just the value type. Let me know if this answer doesn't do what you want here: https://stackoverflow.com/a/75896691/1696171 – Eric Cochran Mar 31 '23 at 19:30

0 Answers0