Gson 在我的对象中将 HashMap<Integer> 转换为 HashMap<String>

Gson converts the HashMap<Integer> to HashMap<String> inside my Object

我有一个对象,里面有一张地图:

MyDTO 
   HashMap<Integer> 

现在,当我将我的 MyDTO 转换为 JSON(使用 Gson),然后从 JSON 返回到 MyDTO 时,我得到的是 HashMap<String>.

我从 JSON 转换回这样的对象:

MyDTO dto = gson.fromJson(json, MyDTO.class);

我如何强制它 convert/keep DTO 内的地图作为 Map<Integer> 而不是 Map<String>

这是我的对象:

public class MultiSeriesTimebasedChartDTO implements Serializable
 {

    LinkedHashMap<String, ArrayList<Number>> data;
}

以下是我将 JSON 转换回对象的方法:

multiSeriesTimebasedChartDTO = gson.fromJson(json, MultiSeriesTimebasedChartDTO.class);

这是结果(在屏幕截图中),它是数字,但现在是字符串。我需要它们作为数字返回。

因此为此寻找一种干净的方法。

我绝对可以遍历它,将每个数字从字符串改回数字,然后替换它...但我在想可能还有其他更好的方法。

解析完JSON后,仍然是java.lang.Number秒。但是,由于您的字段具有 LinkedHashMap<String, ArrayList<<b>Number</b>>> 类型,Gson 使用其内部类型 LazilyParsedNumber 因为它无法知道您希望将 Number 解析为哪种特定类型。 LazilyParsedNumber 充当 JSON 字符串表示的包装器,因此您可以调用相应的 Number 方法来解析值。

LazilyParsedNumber 如果您只检索它的 intValue()doubleValue() ... 应该就足够了,但是如果想将它与其他数字进行比较,它不会起作用,因为 LazilyParsedNumber 只等于它自己。

由于您的问题提到 Map 包含 Integer 值,最简单的解决方案是更改 DTO 字段的类型:

LinkedHashMap<String, ArrayList<Integer>>

这样 Gson 就知道您想要的确切数字类型,并且可以正确地将 JSON 数字反序列化为整数。

你没有任何可能的“HashMap<Integer>”,你有ArrayList<Number>,这就是GSON必须准备的:

public class MultiSeriesTimebasedChartDTO implements Serializable{
  LinkedHashMap<String, ArrayList<Number>> data;
                        ^^^^^^^^^^^^^^^^^
}

此外,您没有 String 所抱怨的,这些是 LazilyParsedNumber

虽然它确实将值存储为字符串,但 class 确实是 Number。你不用担心它的私有成员变量。

public final class LazilyParsedNumber extends Number { // <= extends Number
  private final String value;  // <= this is what you see in the debugger

但这只是对现在的解释。如果你想让 GSON 为你生成一个 Integer 的列表,你应该简单地写成:

public class MultiSeriesTimebasedChartDTO implements Serializable{
  LinkedHashMap<String, ArrayList<Integer>> data;
}

请记住,GSON 只能分析 class 的声明,它无法猜测您稍后是否确保所有这些泛型数字都是整数。