我在Gson上使用Retrofit,并且有一个Json对象,例如:“ fees”:[[0,0.26],[50000,0.24],[100000,0.22]]
如何使用Gson将其反序列化为元组数组。像这样。

public class MyClass{
    public List<MyTuple> Fees;
}

public class MyTuple{
    public int volume;
    public double percentFee;
}

最佳答案

创建一个自定义的Gson Deserializer解决了我的问题。这是代码:

 GsonBuilder gsonBuilder = new GsonBuilder();
 gsonBuilder.registerTypeAdapter(MyTuple.class, new MyTupleDeserializer());
 Gson gson = gsonBuilder.create();
 MyClass myClass= gson.fromJson(json, MyClass.class);


这是MyTupleDeserializer类的代码

 private class MyTupleDeserializer implements JsonDeserializer<MyTuple> {
    @Override
    public MyTuple deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonArray tupleValues= json.getAsJsonArray();
        MyTuple myTuple= new MyTuple();
        myTuple.setVolume(tupleValues.get(0).getAsInt());
        myTuple.setPercentFee(tupleValues.get(1).getAsDouble());
        return myTuple;
    }
}

08-18 11:20