如果每个列表都有如下结构:
{
"images": {
"edges": [
{
"node": {
"entry": "entry-value"
}
}
]
}
}
每个列表都是带有edges 属性的JSON Object,数组中的每个元素都由带有node 属性的JSON Object 包装。对于这种结构,我们可以编写类似于Jackson - deserialize inner list of objects to list of one higher level question 中的通用反序列化器。
例如Set解串器:
class InnerSetDeserializer extends JsonDeserializer<Set> implements ContextualDeserializer {
private final JavaType propertyType;
public InnerSetDeserializer() {
this(null);
}
public InnerSetDeserializer(JavaType propertyType) {
this.propertyType = propertyType;
}
@Override
public Set deserialize(JsonParser p, DeserializationContext context) throws IOException {
p.nextToken(); // SKIP START_OBJECT
p.nextToken(); // SKIP any FIELD_NAME
CollectionType collectionType = getCollectionType(context);
List<Map<String, Object>> list = context.readValue(p, collectionType);
p.nextToken(); // SKIP END_OBJECT
return list.stream().map(Map::values).flatMap(Collection::stream).collect(Collectors.toSet());
}
private CollectionType getCollectionType(DeserializationContext context) {
TypeFactory typeFactory = context.getTypeFactory();
MapType mapType =
typeFactory.constructMapType(
Map.class, String.class, propertyType.getContentType().getRawClass());
return typeFactory.constructCollectionType(List.class, mapType);
}
@Override
public JsonDeserializer<?> createContextual(DeserializationContext context, BeanProperty property) {
return new InnerSetDeserializer(property.getType());
}
}
我们可以使用如下:
class Product {
private String id;
private String vendor;
@JsonDeserialize(using = InnerSetDeserializer.class)
private Set<Image> images;
// getters, setters
}
示例应用:
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.databind.type.MapType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class JsonApp {
public static void main(String[] args) throws IOException {
File jsonFile = new File("./resources/test.json");
ObjectMapper mapper = new ObjectMapper();
Product product = mapper.readValue(jsonFile, Product.class);
System.out.println(product);
}
}
上面的代码打印:
Product{id='gid://mysite/Product/1853361520730', vendor='gadgetdown', images=[Image{originalSrc='https://cdn.something.com'}, Image{originalSrc='https://cdn.something.com'}]}