Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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>() {});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...