java中使用FastJSON将JSON转为List或Set泛型对象类型

     使用FastJSON将字符串类型的JSON对象转为泛型对象类型,需要特殊处理下才能正常转换。

json使用的是fastjson,json转换对象的时候,如果对象中存在泛型对象,则需要特殊处理下才能正常转换。

     使用的是fastjson中的TypeReference来进行转换:

A<B<C>> resultObj =JSON.parseObject("转换json",new TypeReference<A<B<C>>>(){});

其中A为接收类型,B为A的泛型类,C为B的泛型类

     例如:将

{"code":"0","msg":null,"data":["a36a655206394154a14918d6aa6d73f41"]}

     转为

public class ActionResult<T> implements Serializable {

    private static final long serialVersionUID = 5744675651322306036L;

    private String code;

    private String msg;

    private T data;
}

     泛型接受为Set类型时,可以使用

String resultString = "{\"code\":\"0\",\"msg\":null,\"data\":[\"a36a655206394154a14918d6aa6d73f41\"]}";

ActionResult<Set<String>>result = JSON.parseObject(resultString,new TypeReference<ActionResult<Set<String>>>(){});

      当然也可以转为List类型

发布了225 篇原创文章 · 获赞 30 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_35634181/article/details/104005539