Java : Convert Object consisting enum to Json Object

It seems JSONObject doesn't support enums. You could alter your Job class to add a getter like this:

public String getStatus() {
    return status.name();
}

then, invoking new JSONObject(job).toString() produces:

{"id":"12345","status":"INPROGRESS"}

ObjectMapper mapper= new ObjectMapper();

new JSONObject(mapper.writeValueAsString(job));

would do the trick. Now Enums and DateTime types looks normal and is converted properly in json objects.

I came to this page as a person seeking answer and my research helped me to answer this question.


First of all I highly recommend do not use this library (org.json), this is very old and unsupported (as i know) library. I suggest Jackson or Gson.

But if you really need JSONObject, you can add getter into enum:

 public enum JobStatus implements Serializable{
    INCOMPLETE,
    INPROGRESS,
    ABORTED,
    COMPLETED;

    public String getStatus() {
        return this.name();
    }
}

result of serialization:

{"id":"12345","status":{"status":"INPROGRESS"}}

As I know, JSONObject don't support correct serialization of enums which not have any additional data inside.

Tags:

Java

Enums

Json