Java:将包含的枚举对象转换为Json对象 [英] Java : Convert Object consisting enum to Json Object

查看:1324
本文介绍了Java:将包含的枚举对象转换为Json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用org.json库将Object转换为Json格式。请仔细检查以下代码片段。

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());

它显示如下输出:

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

它显示空白并添加Curly基数。这是什么意思?有人经历了这个问题吗?

It shows blank and adds Curly bases. What does it mean? Is anybody gone through this problem?

推荐答案

首先我强烈建议不要使用这个库(org.json),这是非常老,不支持(如我所知)图书馆。我建议杰克逊 Gson

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.

但是,如果您真的需要JSONObject,可以将getter添加到枚举中:

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();
    }
}

序列化结果:

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

如我所知,JSONObject不支持正确的序列化枚举,其中没有任何其他数据。

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

这篇关于Java:将包含的枚举对象转换为Json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆