2012-05-10 13 views
0
import org.json.simple.JSONArray; 
import org.json.simple.JSONAware; 
import org.json.simple.JSONObject; 
import org.json.simple.JSONValue; 

public class JsonTest implements JSONAware { 
private final int x, y; 

public JsonTest(int x, int y) { 
    this.x = x; 
    this.y = y; 
} 

@Override 
public String toJSONString() { 
    JSONArray arr = new JSONArray(); 
    arr.add(this.x); 
    arr.add(this.y); 
    return arr.toString(); 
} 

public static void main(String[] args) { 
    JsonTest jtest = new JsonTest(4, 5); 
    String test1 = JSONValue.toJSONString(jtest); 
    System.out.println(test1); //this works as expected 
    JSONObject obj = new JSONObject(); 
    obj.put(jtest, "42"); 
    System.out.println(obj); //this doesn't 
} 
} 

給出作爲輸出:爲什麼JSONObject不能編碼我的類?

[4,5]

{ 「[email protected]」: 「42」}

相反的:

[4,5]

{[4,5]:「42」}

我在想什麼?

我參考:http://code.google.com/p/json-simple/wiki/EncodingExamples#Example_6-1_-_Customize_JSON_outputs

+1

'[4,5]'沒有有效的JSON標識符! – Sirko

回答

3

這是因爲JSonTest不會覆蓋toString()方法。

下面的代碼添加到JSonTest類:

@Override 
public String toString() { 
    return toJSONString(); 
} 
+0

不應該「實現JSONAware」是在這種情況下去正確的方式嗎? - http://code.google.com/p/json-simple/wiki/EncodingExamples#Example_6-1_-_Customize_JSON_outputs – Enoon

+0

'JSONAware'不覆蓋'toString()'方法,'JSONObject'調用'toString( )'方法(在你的代碼示例中顯然可見)。 –

+0

@FabioMariaCarlucci:實現一個接口不會自動包含一個自定義的toString(),並且'Object.toString()'不會做你想做的。 – delicateLatticeworkFever

0

因爲只有一個字符串可以用作JSON對象的密鑰。所以你的jtest對象被轉換成String。

+0

因爲它調用對象的'toString()'方法。 –

相關問題