I am using org.json library to convert Object to Json format. Kindly check the below code snippet.
public enum JobStatus implements Serializable{ INCOMPLETE, INPROGRESS, ABORTED, COMPLETED } public class Job implements Serializable { private string id; private JobStatus status; ... } ... // Create Job Object Job job = new Job("12345", JobStatus.INPROGRESS); // Convert and print in JSON format System.out.println(new JSONObject(job).toString());
It shows the output like this :
{"id":"12345", "status" : {}}
It shows blank and adds Curly bases. What does it mean? Is anybody gone through this problem?
JSON has no enum type. The two ways of modeling an enum would be: An array, as you have currently. The array values are the elements, and the element identifiers would be represented by the array indexes of the values.
All you have to do is create a static method annotated with @JsonCreator in your enum. This should accept a parameter (the enum value) and return the corresponding enum. This method overrides the default mapping of Enum name to a json attribute .
The @JsonValue annotation is one of the annotations which we can use for both serializing and deserializing enums. Enum values are constants, and due to this, @JsonValue annotation can be used for both. First we simply add the getter method to our Distance. java by using the @JsonValue annotation.
The ObjectMapper class of the Jackson API provides methods to convert the Java object to JSON format or object. The ObjectMapper class writeValueAsString() method takes the JSON object as a parameter and returns its respective JSON string.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With