Search code examples
solrsolrj

How to transform SimpleOrderedMap into JSON string or JSON object?


Is there any standard way to do so?


Solution

  • In short: no, because JSON doesn't have a primitive ordered map type.

    The first step is to determine the requirements of your client, as far as decoding the JSON string goes. Since the JSON specification doesn't have an ordered map type, you'll have to decide on a representation to use. The choice you make will depend on the decoding requirements of your client.

    If you have full control over the decoding of the JSON string, you can simply encode the object into a map in order, using a JSON library that is guaranteed to serialize things in the order of an iterator that you pass in.

    If you can't guarantee this, you should come up with a representation on your own. Two simple examples are:

    An alternating list:

    "[key1, value1, key2, value2]"
    

    A list of key/value entry objects:

    "[{key: key1, val:value1}, {key: key2, val:value2}]"
    

    Once you've come up with this representation, it's easy to write a simple function that loops over your SimpleOrderedMap. For example :

    JSONArray jarray = new JSONArray();
    for(Map.Entry e : simpleOrderedMap) {
        jarray.put(e.key());
        jarray.put(e.value());
    }