Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

java - How to (completely) deserialize json into a generic List?

When using an ObjectMapper to transform a json String into an entity, I can make it generic as:

public <E> E getConvertedAs(String body, Class<E> type) throws IOException {
    return mapper.readValue(body, type);
}

Now let's say I want to read collections. I can do:

List<SomeEntity> someEntityList = asList(mapper.readValue(body, SomeEntity[].class));
List<SomeOtherEntity> someOtherEntityList = asList(mapper.readValue(body, SomeOtherEntity[].class));

I would like to write an equivalent method of the above, but for collections. Since you can't have generic arrays in java, something like this won't work:

public <E> List<E> getConvertedListAs(String body, Class<E> type) {
    return mapper.readValue(body, type[].class);
}

Here there is a solution that almost works:

mapper.readValue(jsonString, new TypeReference<List<EntryType>>() {});

The problem is that it doesn't deserialize into a list of E, but of LinkedHashMap.Entry. Is there any way of going going a step further, something like the following?

public <E> List<E> getConvertedListAs(String body, Class<E> type) {
    mapper.readValue(body, new TypeReference<List<type>>() {}); // Doesn't compile
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This method can help to read json to an object or collections:

public class JsonUtil {
    private static final ObjectMapper mapper = new ObjectMapper();

    public static <T>T toObject(String json, TypeReference<T> typeRef){
        T t = null;
        try {
            t = mapper.readValue(json, typeRef);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }
}

Read json to list:

List<Device> devices= JsonUtil.toObject(jsonString,
                            new TypeReference<List<Device>>() {});

Read json to object:

Device device= JsonUtil.toObject(jsonString,
                                new TypeReference<Device>() {});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...