将JSONObject转换为值为0.0的String

时间:2015-09-01 08:12:13

标签: java json

当我有以下JSONObject(org.json)时,我遇到了这个问题:

{
"float1": 0.0,
"float2": 0.1
}

当我在对象上调用toString方法时,我得到了字符串:

{"float1": 0,"float2": 0.1}

所以0.0被转换为0,这给我带来了很多问题。有人知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

我认为这就是你想要的。但是这个解决方案会强制你使用从JSONObject扩展的自己的类,它的唯一功能是覆盖JSONObject的toString()方法,我不知道它是否值得。

import org.json.JSONObject;
import org.json.JSONException;

public class Test extends JSONObject {
    public Test(String in) throws JSONException {
        super(in);
    }

    public static Test jsonObj = null;

    public static void main(String[] args) throws JSONException {
        jsonObj = new Test("{float1: 0.0, float2: 0.1}");
        System.out.println(jsonObj.toString());
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        String[] box = JSONObject.getNames(jsonObj);
        for (int i = 0; i < JSONObject.getNames(jsonObj).length; i++) {
            try {
                sb.append(box[i])
                        .append(" ")
                        .append(String.format(Locale.ENGLISH, "%.1f",
                                jsonObj.get(box[i])))
                        .append(i != JSONObject.getNames(jsonObj).length - 1 ? ","
                                : "");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        sb.append("}");
        return sb.toString();

    }

}

答案 1 :(得分:0)

我会尝试Gson来实现它。

Gson gson = new GsonBuilder().registerTypeAdapter(Double.class, new DoubleSerializer()).create();
TestBean bean = gson.fromJson(jsonInput, TestBean.class);
String jsonOutput = gson.toJson(bean);

DoubleSerializer:

    class DoubleSerializer implements JsonSerializer<Double> {
    public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(String.format("%.1f", src));
      }
}

TestBean.java:

 public class TestBean {
    private Double float1;
    private Double float2;

    public Double getFloat1() {
        return float1;
    }
    public void setFloat1(Double float1) {
        this.float1 = float1;
    }
    public Double getFloat2() {
        return float2;
    }
    public void setFloat2(Double float2) {
        this.float2 = float2;
    }   
}

如果jsonInput是

{
 "float1": 0.0, 
 "float2": 1.31
}

jsonOutput将是:

{
   "float1": "0.0",
   "float2": "1.3"
}