2015-09-01 33 views
0

我碰到的時候,我有以下的JSONObject(org.json)問題:轉換的JSONObject到字符串,其中價值爲0.0

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

當我在對象上調用toString方法我得到的字符串:

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

因此0.0被轉換爲0,這對我造成很多問題。有人知道如何解決這個問題嗎?

+2

它不應該引起你的問題。數字0和0.0是相同的。問題是什麼?什麼是相關代碼? –

+0

讓我們想象兩個jsons,一個是我們說的模式,另一個是一些處理的結果。我的測試工具(JSON比較器)需要兩個不同的「0.0」.equals(「0」)的JSON字符串是假的 – user3450486

+1

自然的後續將是爲什麼你比較字符串,而不是比較值? –

回答

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(); 

    } 

} 
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" 
} 
相關問題