当我尝试将字符串转换为json时,Gson有一些奇怪的行为.下面的代码将字符串草稿转换为json响应.有没有办法阻止gson将'.0添加到所有整数值?
ArrayList<Hashtable<String, Object>> responses;
Type ResponseList = new TypeToken<ArrayList<Hashtable<String, Object>>>() {}.getType();
responses = new Gson().fromJson(draft, ResponseList);
draft:
[ {"id":4077395,"field_id":242566,"body":""},
{"id":4077398,"field_id":242569,"body":[[273019,0],[273020,1],[273021,0]]},
{"id":4077399,"field_id":242570,"body":[[273022,0],[273023,1],[273024,0]]}
]
responses:
[ {id=4077395.0, body=, field_id=242566.0},
{id=4077398.0, body=[[273019.0, 0.0], [273020.0, 1.0], [273021.0, 0.0]], field_id=242569.0},
{id=4077399.0, body=[[273022.0, 0.0], [273023.0, 1.0], [273024.0, 0.0]], field_id=242570.0}
]
Run Code Online (Sandbox Code Playgroud) 我的json中有整数,我不希望gson将它们转换成双打.以下不起作用:
@Test
public void keepsIntsAsIs(){
String json="[{\"id\":1,\"quantity\":2,\"name\":\"apple\"},{\"id\":3,\"quantity\":4,\"name\":\"orange\"}]";
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Double.class, new DoubleSerializerAsInt());
Gson gson = gsonBuilder.create();
List<Map<String, Object>> l = gson.fromJson(json, List.class);
for(Map<String, Object> item : l){
System.out.println(item);
}
}
private static class DoubleSerializerAsInt implements JsonSerializer<Double>{
@Override
public JsonElement serialize(Double aDouble, Type type, JsonSerializationContext jsonSerializationContext) {
int value = (int)Math.round(aDouble);
return new JsonPrimitive(value);
}
}
Run Code Online (Sandbox Code Playgroud)
输出不是我想要的:
{id=1.0, quantity=2.0, name=apple}
{id=3.0, quantity=4.0, name=orange}
Run Code Online (Sandbox Code Playgroud)
有没有办法在我的地图中使用整数而不是双打?
{id=1, quantity=2, name=apple}
{id=3, quantity=4, name=orange}
Run Code Online (Sandbox Code Playgroud)
编辑:并非所有字段都是整数.我相应地修改了我的例子.我在网上看了很多例子,包括这个网站上的一些答案,但在这个特殊情况下它不起作用.