我有一个要转换为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;
    }
}


我使用JSONObject body = new JSONObject(responseEntity);将其转换为json,但出现了“构造函数JSONObject(CourseKeyInfo)未定义”错误。知道如何将课程转换为json吗?

最佳答案

如果使用GSON,则可以执行以下操作:

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


为了这个工作


下载GSON JAR
添加到您的项目构建路径
就这样


结果是:

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

08-19 05:28