我创建了一个简单的 POJO:
public class LoginPojo {
private String login_request = null;
private String email = null;
private String password = null;
// getters, setters
}
经过一番搜索,我发现了这个:JSONObject jsonObj = new JSONObject( loginPojo );
但是有了这个我得到了错误:
The constructor JSONObject(LoginPojo) is undefined
我找到了另一个解决方案:
JSONObject loginJson = new JSONObject();
loginJson.append(loginPojo);
但是这个方法不存在。
那么如何将我的 POJO 转换为 JSON?
最佳答案
只需使用java Gson API :
Gson gson = new GsonBuilder().create();
String json = gson.toJson(obj);// obj is your object
然后您可以从这个 json String
创建一个 JSONObject
,如下所示:
JSONObject jsonObj = new JSONObject(json);
看看Gson user guide还有这个SIMPLE GSON EXAMPLE获取更多信息。
关于java - 从 POJO 创建 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27036857/