Java:将包含枚举的对象转换为 Json 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30871013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java : Convert Object consisting enum to Json Object
提问by Ronnie
I am using org.json library to convert Object to Json format. Kindly check the below code snippet.
我正在使用 org.json 库将 Object 转换为 Json 格式。请检查以下代码片段。
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?
它显示空白并添加卷曲碱基。这是什么意思?有人经历过这个问题吗?
采纳答案by Denys Denysiuk
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 Hymansonor Gson.
首先,我强烈建议不要使用这个库(org.json),这是一个非常古老且不受支持(据我所知)的库。我建议Hymanson或Gson。
But if you really need JSONObject, you can add getter into enum:
但是如果你真的需要 JSONObject,你可以在 enum 中添加 getter:
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.
据我所知,JSONObject 不支持内部没有任何附加数据的枚举的正确序列化。
回答by Bohemian
It seems JSONObject
doesn't support enums. You could alter your Job
class to add a getter like this:
似乎JSONObject
不支持枚举。你可以改变你的Job
类来添加一个这样的吸气剂:
public String getStatus() {
return status.name();
}
then, invoking new JSONObject(job).toString()
produces:
然后,调用new JSONObject(job).toString()
产生:
{"id":"12345","status":"INPROGRESS"}
回答by Hari
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.
会做的伎俩。现在Enums
和DateTime
类型看起来正常并且在 json 对象中正确转换。
I came to this page as a person seeking answer and my research helped me to answer this question.
我是作为一个寻求答案的人来到这个页面的,我的研究帮助我回答了这个问题。
回答by Ahmed Adel Ismail
for me, i made an interface that shuold be implemented by any enum i will have to use in Json, this interface forces the enum to know the proper enum itself from a value, and also it should return a value ... so every enum.CONSTANT is mapped to a value of any type (weather a number or a String)
对我来说,我创建了一个接口,它可以由我必须在 Json 中使用的任何枚举实现,这个接口强制枚举从一个值中知道正确的枚举本身,并且它应该返回一个值......所以每个枚举.CONSTANT 映射到任何类型的值(天气数字或字符串)
so when i want to put this enum in a Json Object, i ask the enum.CONSTANT to give me it's value, and when i have this value (from Json), i can request from the enum to give me the proper enum.CONSTANT mapped to this value
所以当我想把这个枚举放在一个 Json 对象中时,我要求 enum.CONSTANT 给我它的值,当我有这个值(来自 Json)时,我可以从枚举请求给我正确的 enum.CONSTANT映射到这个值
the interface is as follows (you can copy it as it is) :
界面如下(可以原样复制):
/**
*
* this interface is intended for {@code enums} (or similar classes that needs
* to be identified by a value) who are based on a value for each constant,
* where it has the utility methods to identify the type ({@code enum} constant)
* based on the value passed, and can declare it's value in the interface as
* well
*
* @param <T>
* the type of the constants (pass the {@code enum} as a type)
* @param <V>
* the type of the value which identifies this constant
*/
public interface Valueable<T extends Valueable<T, V>, V> {
/**
* get the Type based on the passed value
*
* @param value
* the value that identifies the Type
* @return the Type
*/
T getType(V value);
/**
* get the value that identifies this type
*
* @return a value that can be used later in {@link #getType(Object)}
*/
V getValue();
}
now here is an example for a small enum implementing this interface:
现在这里是一个实现这个接口的小枚举的例子:
public enum AreaType implements Valueable<AreaType, Integer> {
NONE(0),
AREA(1),
NEIGHBORHOOD(2);
private int value;
AreaType(int value) {
this.value = value;
}
@Override
public AreaType getType(Integer value) {
if(value == null){
// assume this is the default
return NONE;
}
for(AreaType a : values()){
if(a.value == value){ // or you can use value.equals(a.value)
return a;
}
}
// assume this is the default
return NONE;
}
@Override
public Integer getValue() {
return value;
}
}
to save this enum in a Json :
将此枚举保存在 Json 中:
AreaType areaType = ...;
jsonObject.put(TAG,areaType.getValue());
now to get your value from a Json Object :
现在从 Json 对象中获取您的价值:
int areaValue = jsonObject.optInt(TAG,-1);
AreaType areaType = AreaType.NONE.getType(areaValue);
so if the areaValue is 1 for example, the AreaType will be "Area", and so on
例如,如果 areaValue 为 1,则 AreaType 将为“Area”,依此类推
回答by Niraj Sonawane
Similar to what @Denys Denysiuk has answered. But if you want to return any value instead of StringWe can use like this. In below example i wanted to return value 1, or 15 instead of String
类似于@Denys Denysiuk 的回答。但是如果你想返回任何值而不是 String我们可以这样使用。在下面的示例中,我想返回值 1 或 15 而不是字符串
@Getter
public enum PaymentCollectionDay {
FIRST_OF_MONTH(1), FIFTEENTH_OF_MONTH(15);
PaymentCollectionDay(int day) {
this.day = day;
}
@JsonValue
final int day;
}