Java object to JSON with org.json lib

前端 未结 2 1305
半阙折子戏
半阙折子戏 2021-02-20 17:16

I have class like this:

public class Class1 {
    private String result;
    private String ip;
    private ArrayList alarm;
}

Wh

2条回答
  •  清歌不尽
    2021-02-20 17:50

    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.

提交回复
热议问题