com.google.gson.internal.LinkedTreeMap 无法投射到我的班级 [英] com.google.gson.internal.LinkedTreeMap cannot be cast to my class

查看:132
本文介绍了com.google.gson.internal.LinkedTreeMap 无法投射到我的班级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some problems with getting my object from a JSON string.

我得到了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);
    }
}    

从我的服务器上,我得到一个 JSON 字符串表示形式的 ArrayList.例如:

From my server I get an ArrayList<Product> in JSON String representation. For example:

[{"mBarcode":"123","mName":"Apfel","mPrice":"2.7"},
{"mBarcode":"456","mName":"Pfirsich","mPrice":"1.1111"},
{"mBarcode":"89325982","mName":"Birne","mPrice":"1.5555"}] 

这个字符串是这样生成的:

This String is generated like this:

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

为了取回我的对象​​,我使用了这个函数:

To get my Object back I use this function:

public static <T> ArrayList<T> stringToArray(String s) {
    Gson g = new Gson();
    Type listType = new TypeToken<ArrayList<T>>(){}.getType();
    ArrayList<T> list = g.fromJson(s, listType);
    return list;
}

但是当调用

String name = Util.stringToArray(message).get(i).getName();

我收到错误com.google.gson.internal.LinkedTreeMap 无法转换为 object.Product

我做错了什么?看起来它创建了一个 LinkedTreeMap 列表,但我如何将它们转换为我的产品对象?

What am I doing wrong? It looks like it created a List of LinkedTreeMaps but how do i convert those into my Product Object?

推荐答案

在我看来,由于类型擦除,解析器无法在运行时获取真正的类型 T.一种解决方法是提供类类型作为方法的参数.

In my opinion, due to type erasure, the parser can't fetch the real type T at runtime. One workaround would be to provide the class type as parameter to the method.

这样的方法有效,当然还有其他可能的解决方法,但我觉得这个方法非常清晰简洁.

Something like this works, there are certainly other possible workarounds but I find this one very clear and concise.

public static <T> List<T> stringToArray(String s, Class<T[]> clazz) {
    T[] arr = new Gson().fromJson(s, clazz);
    return Arrays.asList(arr); //or return Arrays.asList(new Gson().fromJson(s, clazz)); for a one-liner
}

并称之为:

String name = stringToArray(message, Product[].class).get(0).getName();

这篇关于com.google.gson.internal.LinkedTreeMap 无法投射到我的班级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆