一个复杂的json字符串,我想将其转换为map,
我有个问题.
请看这个简单的测试:
public class Test {
@SuppressWarnings("serial")
public static void main(String[] args) {
Map<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("data", "{\"rowNum\":0,\"colNum\":2,\"text\":\"math\"}");
Map<String,Object> dataMap = JsonUtil.getGson().fromJson(
hashMap.get("data").toString(),new TypeToken<Map<String,Object>>() {}.getType());
System.out.println(dataMap.toString());
}
}
结果:
控制台打印:{rowNum = 0.0,colNum = 2.0,text = math}
Int转换为Double;
为什么gson会更改类型,我该如何解决?
解决方法:
Gson是一个简单的解析器.如果要将数据解析为对象,它将始终使用Double作为默认数字类型.
请查看此问题以获取更多信息:How to prevent Gson from expressing integers as floats
我建议您使用Jackson Mapper.即使您正在解析到对象,Jackson也可以区分类型:
>“ 2”为整数
>“ 2.0”为双精度
这是一个例子:
Map<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("data", "{\"rowNum\":0,\"colNum\":2,\"text\":\"math\"}");
ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {};
HashMap<String, Object> o = mapper.readValue(hashMap.get("data").toString(), typeRef);
行家:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>