我有一个类要转换为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吗?
答案 0 :(得分:3)
构造函数JSONObject(Object)确实存在。
CourseKeyInfo courseKeyInfo = new CourseKeyInfo("This Works!", "101");
JSONObject jsonObject = new JSONObject(courseKeyInfo);
答案 1 :(得分:2)
如果您使用GSON,则可以执行以下操作:
CourseKeyInfo courseKeyInfo = new CourseKeyInfo("This Works!", "101");
String json = new Gson().toJson(courseKeyInfo);
System.out.println(json);
让它工作
结果是:
{"courseKey":"This Works!","institutionID":"101"}
答案 2 :(得分:1)
这里的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());