Java object to JSON with org.json lib

≯℡__Kan透↙ 提交于 2019-12-04 02:48:10
BuffaloBuffalo

I think the utilizing org.json.lib's JSONObject(Object) constructor is what you're looking for. It will construct a JSONObject from your Java Object based on its getters. You can then use JSONObject#toString to get the actual Json produced.

JSONObject jsonObject = new JSONObject(instanceOfClass1);
String myJson = jsonObject.toString();

While JSONObject is the way to go, you need to follow what its JavaDoc says about bean properties:

Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object. For each of the methods with no parameters and a name starting with "get" or "is" followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method are put into the new JSONObject. The key is formed by removing the "get" or "is" prefix. If the second remaining character is not upper case, then the first character is converted to lower case. For example, if an object has a method named "getName", and if the result of calling object.getName() is "Larry Fine", then the JSONObject will contain "name": "Larry Fine".

Based on the documentation, it will fail in your case because you don't expose those properties via gettings and setters.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!