相关疑难解决方法(0)

com.google.gson.internal.LinkedTreeMap无法投射到我的班级

从JSON字符串获取对象时遇到一些问题.

我上了课 Product

public class Product {
    private String mBarcode;
    private String mName;
    private String mPrice;

    public Product(String barcode, String name, String price) {
        mBarcode = barcode;
        mName = name;
        mPrice = price;
    }

    public int getBarcode() {
        return Integer.parseInt(mBarcode);
    }

    public String getName() {
        return mName;
    }

    public double getPrice() {
        return Double.parseDouble(mPrice);
    }
}    
Run Code Online (Sandbox Code Playgroud)

从我的服务器,我得到一个ArrayList<Product>JSON字符串表示.例如:

[{"mBarcode":"123","mName":"Apfel","mPrice":"2.7"},
{"mBarcode":"456","mName":"Pfirsich","mPrice":"1.1111"},
{"mBarcode":"89325982","mName":"Birne","mPrice":"1.5555"}] 
Run Code Online (Sandbox Code Playgroud)

此String生成如下:

public static <T> String arrayToString(ArrayList<T> list) {
    Gson g = new Gson();
    return g.toJson(list);
}
Run Code Online (Sandbox Code Playgroud)

为了让我的对象回来,我使用这个函数:

public …
Run Code Online (Sandbox Code Playgroud)

java json casting gson

54
推荐指数
4
解决办法
6万
查看次数

Java Type Generic作为GSON的参数

在GSON中获取您执行的对象列表

Gson gson = new Gson();
Type token = new TypeToken<List<MyType>>(){}.getType();
return gson.fromJson(json, token);
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但我想更进一步,让MyType参数化,这样我就可以有一个通用的函数来解析这个代码的对象列表

// the common function 
public <T> List<T> fromJSonList(String json, Class<T> type) {
  Gson gson = new Gson();
  Type collectionType = new TypeToken<List<T>>(){}.getType();
  return gson.fromJson(json, collectionType);
}

// the call
List<MyType> myTypes = parser.fromJSonList(jsonString, MyType.class);
Run Code Online (Sandbox Code Playgroud)

遗憾地返回一个StringMaps数组,而不是类型.T被解释为另一种泛型类型,而不是我的类型.任何解决方法?

java generics gson

48
推荐指数
6
解决办法
4万
查看次数

如何获得具体类型的通用接口

我有一个界面

public interface FooBar<T> { }
Run Code Online (Sandbox Code Playgroud)

我有一个实现它的类

public class BarFoo implements FooBar<Person> { }

通过反射,我想获取BarFoo的一个实例并得到它实现的FooBar版本是Person.

我使用.getInterfacesBarFoo回到FooBar,但这并没有帮助我找出T是什么.

java reflection

18
推荐指数
2
解决办法
2万
查看次数

标签 统计

java ×3

gson ×2

casting ×1

generics ×1

json ×1

reflection ×1