简体   繁体   中英

Jackson deserialize mixed array

I have a complex json string that I'm trying to deserialize. A simplified example would be (the data that I'm parsing is much more nested than that):

{
  "content": [
    {
      "value": {
        "name": "name1",
        "subvalue": {
          "id": "id1"
        }
      }
    },
    {
      "reference": "mixed"
    },
    {
      "value": {
        "name": "name2",
        "subvalue": {
          "id": "id2"
        }
      }
    }
  ]
}

I'm trying to deserialize it through a custom deserializer and it works fine except it also fills the array with empty values (the "reference" part I don't need).

Here is my data class:

@JsonDeserialize(using = ResultDeserializer.class)
class ResultInfo {
    public String name;
    public String id;
}

My custom deserializer :

class ResultDeserializer extends JsonDeserializer<ResultInfo> {
    @Override
    public ResultInfo deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException {
        ResultInfo resultInfo = null;
        ObjectCodec mapper = jsonParser.getCodec();
        JsonNode node = mapper.readTree(jsonParser);

        node = node.get("value");

        if (node != null) {
            resultInfo = new ResultInfo();
            resultInfo.name(node.get("name").toString());
            resultInfo.id(node.at("/subvalue/id").toString());
        }

        return resultInfo;
    }

}

However when filling an array using the custom deserializer I'm getting null values in the array:

final CollectionType collectionType =
                TypeFactory
                        .defaultInstance()
                        .constructCollectionType(ArrayList.class, ResultInfo.class);

ArrayList<ResultInfo> resultInfos = null;
try {
   ObjectReader reader = mapper.readerFor(collectionType);
   resultInfos = reader.readValue(rootNode);
} catch (Exception e) {
   Log.e(TAG, "Exception:" + e.getMessage());
}

Is there, for deserialization, an equivalent to :

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

I have also tried adding @JsonInclude(Include.NON_NULL) to my data class without success.

The json example invalid, it should be something like this

{
  "content": [
    {
      "value": {
        "name": "name1",
        "subvalue": {
          "id": "id1"
        }
      }
    },
    {
      "reference": "mixed"
    },
    {
      "value": {
        "name": "name2",
        "subvalue": {
          "id": "id2"
        }
      }
    }
  ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM