Map entries order lost with JSONObject

Issue #168 closed
Aleksandr Beliakov created an issue

Hello,

We are developing a digital signature creation and validation open-source project DSS https://github.com/esig/dss . Currently we are working on the JAdES implementation and use jose4j project.

The problem is that when I instantiate a JSONObject from a LinkedHashMap it loses the order of objects, because JSONObject is extended from a HashMap, what does not support the ordering.

Map<String, Object> sigDParams = new LinkedHashMap<>();
sigDParams.put(JAdESHeaderParameterNames.M_ID, SigDMechanism.OBJECT_ID_BY_URI_HASH.getUri());
...
JSONObject jsonObject = new JSONObject(sigDParams);

In the resulting jsonObject I want to be sure that the first added entry 'M_ID' will be on the first place of the map.

We would like to propose to change JSONObject class design to a wrapper pattern, by instantiating it with a provided Map like following:

public class JSONObject implements ... {

  private Map map;

  public JSONObject() {
        map = new HashMap<>();
  }

  public JSONObject(Map m) {
        map = m;
  }

  ...

}

The potential problem with this solution that it does not respect the statement in the JSONObject(Map m) constructor’s javaDoc:

Allows creation of a JSONObject from a Map. After that, both the generated JSONObject and the Map can be modified independently.

With this constructor you will be forced to use the same instance of a map. However one still would be able to use the maps independently, by instantiating an empty constructor JSONObject() and adding an original map entries with putAll() method.

What do you think about this? Please, feel free to share with us other ideas about the possible resolution of the problem.

Also we are not 100% convinced to have static methods in the JSONObject, should not be it moved to JsonUtil.class?

Best regards,

Aleksandr.

Comments (2)

  1. Brian Campbell

    You should be able to just pass the LinkedHashMap to JsonUtil's toJson(...). The JwtClaims class is also backed by a LinkedHashMap so that might be an option too.

  2. Log in to comment