【问题标题】:How to read List<List<List<Double>> using Parcelable in Android如何在 Android 中使用 Parcelable 读取 List<List<List<Double>>
【发布时间】:2021-12-26 18:18:16
【问题描述】:

在 GET 中检索信息时,我得到了正确的响应。现在,我正在尝试使用 Post 调用将一些数据发送回服务器。但是当我这样做时,我会得到classCastException

这里是模型类

public class Polygon implements Parcelable
{

    @SerializedName("type")
    @Expose
    private String type;
    @SerializedName("coordinates")
    @Expose
    private List<List<List<Double>>> coordinates = new ArrayList<>();
    public final static Creator<Polygon> CREATOR = new Creator<Polygon>() {


        @SuppressWarnings({
                "unchecked"
        })
        public Polygon createFromParcel(android.os.Parcel in) {
            return new Polygon(in);
        }

        public Polygon[] newArray(int size) {
            return (new Polygon[size]);
        }

    };

    protected Polygon(android.os.Parcel in) {
        this.type = ((String) in.readValue((String.class.getClassLoader())));
        in.readList(this.coordinates, (List.class.getClassLoader()));
    }

    public Polygon() {
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public List<List<List<Double>>> getCoordinates() {
        return coordinates;
    }

    public void setCoordinates(List<List<List<Double>>> coordinates) {
        this.coordinates = coordinates;
    }

    public void writeToParcel(android.os.Parcel dest, int flags) {
        dest.writeValue(type);
        dest.writeList(coordinates);
    }

    public int describeContents() {
        return 0;
    }

}

这是我试图检索并稍后发回的 json。

{"polygon": {
"type": "Polygon",
"coordinates": [
[
[
-105.18367,
39.54363
],
[
-105.18367,
39.98435
],
[
-104.33773,
39.98435
],
[
-104.33773,
39.54363
],
[
-105.18367,
39.54363
]
     ]
    ]
  }
}

为此我得到java.lang.ClassCastException: java.lang.Double cannot be cast to java.util.Collection

我尝试将其转换为单独的类以将其用作CREATOR,但随后 GET 调用失败。

任何帮助都会很棒!

【问题讨论】:

    标签: java android parcelable


    【解决方案1】:

    您可能需要实现一个专门的ArrayListParcelable 才能工作。 How to implement Parcelable for a class containing List<List<String>>? 这里接受的答案很好,但您可能想要使用泛型,因此它不仅可以用于String 或在您的实例中Double

    作为旁注,您可能希望研究一个单层解决方案,以便协调这样的事情。

    public class Coordinates implements Parcelable{
        public double x;
        public double y;
        public double z;
        // You get the gist
    }
    List<Coordinates> coordinates = new ArrayList<>();
    

    如果你能做到这一点,你就可以完全避免上述问题。再说一次,我不知道你的设置,我可能完全错了,但是嵌套的 List 并不是世界上最漂亮的东西。

    【讨论】:

    • 我完全同意嵌套列表,但这是我的后端团队提供的!但它奏效了!除了您的答案之外,我还必须将类扩展到 ArrayList 就像链接的答案一样!我很接近,但你的支持帮助了我很大的时间!
    猜你喜欢
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多