I'm using Spring's RestTemplate, to hit a restful webservice and getting non-standard JSON back.
Here is what I mean:
{
...
rules : {
matched : "rule one",
matched : "rule B",
matched : "another rule"
}
...
}
So basically I need this Hash mapped to a list. In my pojo I would like the field to look like this:
private List<String> rules; // once parsed, should contain "rule one",
// "rule B", "another rule", etc
Here is what I have attempted thus far. Here's my serializer:
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class MapValuesToListSerializer extends JsonSerializer<Map<?, ?>> {
@Override
public void serialize(Map<?, ?> map, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
serializerProvider.defaultSerializeValue(map.values(), jsonGenerator);
}
}
And within my POJO, I've annotated my field like this:
@JsonSerialize(using = MapValuesToListSerializer.class)
private List<String> rules;
This doesn't work. The standard fields all serialize correctly, but not the non-standard fields that conform to this field. I'm missing an important piece to this, but I do not know what.
While I completely agree with JB Nizet
when he states, "If it's one of your own web services, fix it." This is just not something within my grasp, due to the powers that be. I would if I could, otherwise, but that isn't up to me. (Nor do I have the personal bandwidth fix this and any other nSize downstream issues with would cause.)
Fortunately, Jackson does come with the tools to do this.
For the field:
@JsonProperty("rules")
@JsonDeserialize(as = List.class, using = BadmapToListDeserializer.class)
private List<String> rules;
The actual deserializer:
public class BadmapToListDeserializer extends JsonDeserializer<List<String>> {
@Override
public List<String> deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException {
List<String> valuesList = new ArrayList<>();
for (JsonToken jsonToken = jsonParser.nextToken(); jsonToken != JsonToken.END_OBJECT; jsonToken = jsonParser.nextToken()) {
if (jsonToken == JsonToken.VALUE_STRING) {
String value = jsonParser.getText();
valuesList.add(value);
}
}
return valuesList;
}
}
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.