首页 > 想给fastjson的parseObject写一个通用的转换方法

想给fastjson的parseObject写一个通用的转换方法

初步是这样设计

public static <T> T FromJson(String json)
    {
        T obj = JSON.parseObject(json, new TypeReference<T>() {});
        return obj;
    }

调用的时候

MyClass cls2 = JsonClass.<MyClass>FromJson(str);

但是发觉使用的时候,传进来的T都无效,最终转出来的obj还是JSONOjbect的类型。

应该怎么个写法?


FastJson的parseObject,不是有提供这个功能吗?像下面这样:

 CollectionListResponse response = JSON.parseObject("{\"collectionId\":159508,\"id\":195,\"index\":0,\"section\":\"HotNews\",\"title\":\"利用皮肤干细胞消灭癌症\"}", CollectionListResponse.class);

将JSON字符串转换成java中的POJO对象。在fastJson中已经有提供好的方法:Json.parseObjec(json字符串,对象.class);使用方式如下:

package json;

import com.alibaba.fastjson.JSON;

public class TestJson {

    String name;
    String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public static void main(String[] args) {
        String jsonStr = "{\"name\":\"james\", \"age\":12}";
        TestJson test = JSON.parseObject(jsonStr, TestJson.class);
        System.out.printf("Name = %s, age = %s", test.getName(), test.getAge());
    }
}

运行后结果如下:

Name = james, age = 12

使用jar包:fastjson-1.1.36.jar包

【热门文章】
【热门文章】