我有一个类,我想将其转换为 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"}
关于java - 在 Java 中将 bean 转换为 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11692303/