Why does JSONObject not encode my class?

1k Views Asked by At
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
}
}

Gives as output:

[4,5]

{"it.integrasistemi.scegliInPianta.etc.JsonTest@3cb89838":"42"}

Instead of:

[4,5]

{[4,5]:"42"}

What am i missing?

My reference: http://code.google.com/p/json-simple/wiki/EncodingExamples#Example_6-1_-_Customize_JSON_outputs

2

There are 2 best solutions below

3
On BEST ANSWER

That's because JSonTest doesn't override the toString() method.

Add the following code to the JSonTest class:

@Override
public String toString() {
    return toJSONString(); 
}
1
On

Because only a String can be used as a key of a JSON object. So your jtest object is transformed to a String.