andy.hu :
A complex json string and I want to convert it to map, I have a problem.
Please look at this simple test:
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());
}
}
result:
console print : {rowNum=0.0, colNum=2.0, text=math}
Int is converted to Double;
Why does gson change the type and how can I fix it?
dieter :
Gson is a simple parser. It uses always Double as a default number type if you are parsing data to Object
.
Check this question for more information: How to prevent Gson from expressing integers as floats
I suggest you to use Jackson Mapper. Jackson distinguish between type even if you are parsing to an Object:
"2"
asInteger
"2.0"
asDouble
Here is an example:
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);
maven:
<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>
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=443287&siteId=1