Skip to content

Tech: How to solve specific problems in your JSON Java code

Sean Leary edited this page Jan 5, 2023 · 1 revision

Table of contents


Objects in collections need to have override option from reflection-based variable detection

Lots more information is available in the original issue: #544

    // This should work without having to modify the library. This solution uses JSONStrings and assumes that you have control over the classes in your collection.

    public class MyPoJo implements org.json.JSONString {
    private String someField; // pretend getters and setters
    private int someOtherField; // pretend getters and setters
    private ZonedDateTime aDate; // pretend getters and setters
    
    @Override
    public String toJSONString() {
        // notice the lack of "someOtherField"
        return "{" + "\"someField\":" + JSONObject.quote(this.someField) + ",\"aDate\":" + JSONObject.quote(formatMyDate()) + "}";
    }

    private String formatMyDate() { /* some implementation that formats your date a specific way */ }
    }

    // then somewhere else in code:
    Collection<MyPoJo> cMP = getACollectionFromSomewhere();

    JSONArray ja = new JSONArray(cMP); // at this point, the items in the JSONArray are still MyPoJo, not a string or JSONObject
    // if you want you can still work with the POJO through the JSONArray

    // the following will cause the `MyPoJo.toJSONString` to be called for each MyPoJo in the list
    // the output will be as you expect with the POJO formatted as we customized.
    return ja.ToString();