在 Java 中将 bean 转换为 Json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11692303/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:05:00  来源:igfitidea点击:

Turning a bean to Json in java

javajson

提问by user1558274

I have a class that I want to turn into JSON, but the constructor does not allow me. The class is called CourseKeyInfo:

我有一个我想变成 JSON 的类,但构造函数不允许我这样做。该类称为 CourseKeyInfo:

public class CourseKeyInfo
{
    private String courseKey;
    private String institutionID;
    public CourseKeyInfo(String courseKey, String institutionId)
    {
        this.courseKey = courseKey;
        this.institutionID = institutionId;
    }
    public String getCourseKey()
    {
        return courseKey;
    }
    public void setCourseKey(String courseKey)
    {
        this.courseKey = courseKey;
    }
    public String getInstitutionID()
    {
        return institutionID;
    }
    public void setInstitutionID(String institutionID)
    {
        this.institutionID = institutionID;
    }
}

I use JSONObject body = new JSONObject(responseEntity);to turn it into json but it give me "The constructor JSONObject(CourseKeyInfo) is undefined" error. Any idea how I can turn my class into json?

我曾经JSONObject body = new JSONObject(responseEntity);把它变成 json 但它给了我“构造函数 JSONObject(CourseKeyInfo) 未定义”错误。知道如何将我的课程变成 json 吗?

回答by Reimeus

The constructor JSONObject(Object)does actually exist.

构造函数JSONObject(Object)确实存在。

CourseKeyInfo courseKeyInfo = new CourseKeyInfo("This Works!", "101");
JSONObject jsonObject = new JSONObject(courseKeyInfo);

回答by sunil

If you use GSON, you can do this is one line as:

如果您使用GSON,则可以在一行中执行以下操作:

CourseKeyInfo courseKeyInfo = new CourseKeyInfo("This Works!", "101");
String json = new Gson().toJson(courseKeyInfo);
System.out.println(json);

for this to work

为了这个工作

  • download GSON JAR
  • Add to your project build path
  • That's all
  • 下载GSON JAR
  • 添加到您的项目构建路径
  • 就这样

and the result is:

结果是:

{"courseKey":"This Works!","institutionID":"101"}

回答by Andrey Borisov

for http request here is example of using json array+ json beans

对于 http 请求,这里是使用 json 数组 + json bean 的示例

JSONArray jsonArray = new JSONArray();
    for (Credentials credentials : ((PropertiesManager) propertiesManager.get()).getJsonPropertiesManager().getAllCredentials()) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("credentialsName", credentials.getName());
        jsonArray.add(jsonObject);
    }

    req.setAttribute(JSON_RESULT_OBJ_ATTR, jsonArray.toString());