我有以下类,我可以按照我想要的方式序列化。
@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;
}
}
已使用以下序列化程序序列化
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();
}
}
此代码将对象序列化为以下内容:
{"number":10,"word":"Working","values":["first","second","third"]}
现在我试图反序列化它,但我不确定如何处理ArrayList部分的处理。到目前为止,我有这样的事情:
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);
}
}
非常感谢任何帮助。
答案 0 :(得分:1)
到目前为止的选项是,因为您有可用的JsonNode,并且您知道已将列表序列化到属性values
中,以迭代values
属性并添加你班上的内容。
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;
}
}