gson - 数组的长值变为浮点值

时间:2016-12-28 10:58:47

标签: java android json gson

我需要创建这种格式的json:

{
  "array": [
    1482922777223,
    0.014221191,
    0.014221191,
    0.014221191
  ]
}

Data.class

public class Data {

   @SerializedName("array")
   @Expose
   private List<Float> array = null;
}

将对象转换为JSON字符串我使用gson库。

List<Float> list = new ArrayList<>();
list.add((float)1482922777223);
list.add(0.014221191);
list.add(0.014221191);
list.add(0.014221191);
Data data = new Data(list);
Gson gson = new Gson();
String json = gson.toJson(data);

结果字符串:

{
  "array": [
    1.4829219E12, <--- HOW TO GET HERE 1482922777223?
    0.014221191,
    0.014221191,
    0.014221191
  ]
}

请帮忙!

1 个答案:

答案 0 :(得分:0)

您需要为TypeAdapter值注册Float

E.g:

GsonBuilder gsonBuilder = new GsonBuilder();        
gsonBuilder.registerTypeAdapter(Float.class,  new JsonSerializer<Float>() {
  @Override
  public JsonElement serialize(final Float src, final Type typeOfSrc, final JsonSerializationContext context) {
      BigDecimal value = BigDecimal.valueOf(src);    
      return new JsonPrimitive(value);
  }
});

Gson gson = gsonBuilder.create();
String json = gson.toJson(data);

输出:

{
  "array": [
    1482922777223,
    0.014221191,
    0.014221191,
    0.014221191
  ]
}