I have the following Class that I can serialize in a way that I want.
@JsonSerialize(using = MySerializer.class)
@JsonDeserialize(using = MyDeserialize.class)
public class TryToSerialize extends ArrayList<String>
{
private int number;
private String word;
public TryToSerialize(){}
public TryToSerialize(int number, String word){
this.number = number;
this.word = word;
}
@JsonProperty
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
@JsonProperty
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
}
It has been serialized with the following serializer
class MySerializer extends JsonSerializer<TryToSerialize>
{
@Override
public void serialize(TryToSerialize toSerialize, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException
{
jgen.writeStartObject();
jgen.writeNumberField("number", toSerialize.getNumber());
jgen.writeStringField("word", toSerialize.getWord());
provider.defaultSerializeField("values", toSerialize.iterator(), jgen);
jgen.writeEndObject();
}
}
This code will serialize the object into the following:
{"number":10,"word":"Working","values":["first","second","third"]}
Now I am trying to deserialize it, but I am unsure of how to handle the processing of the ArrayList portion. So far I have something like this:
class MyDeserialize extends JsonDeserializer<TryToSerialize> {
@Override
public TryToSerialize deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
int number = (Integer) ((IntNode) node.get("number")).numberValue();
String word = node.get("word").asText();
return new TryToSerialize(number, word);
}
}
Any help would be greatly appreciated.
An option with what you have so far is, since you have the JsonNode available and you know that you have serialized the list into the property values
, to iterate over the values
property and add the contents to your class.
class MyDeserializer extends JsonDeserializer<TryToSerialize> {
@Override
public TryToSerialize deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
int number = (Integer) ((IntNode) node.get("number")).getNumberValue();
String word = node.get("word").asText();
TryToSerialize deserialized = new TryToSerialize(number, word);
JsonNode valuesNode = node.get("values");
if (valuesNode.isArray()) {
Iterator<JsonNode> arrayIterator = ((ArrayNode) valuesNode).getElements();
while (arrayIterator.hasNext()) {
deserialized.add(arrayIterator.next().getTextValue());
}
}
return deserialized;
}
}
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.