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
'[4,5]'沒有有效的JSON標識符! – Sirko