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

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


数据类

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
  ]
}


请帮忙!

最佳答案

您需要为TypeAdapter值注册Float

例如:

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
  ]
}

10-05 21:57