Kevin
Kevin

Reputation: 2888

Arrange elements in JSON Object?

I am writing a program in Java in which I need to edit a JSON input and then resubmit it via a POST to a different system. In my code I use a HashMap that has a key:value pair in which I update a JSONArray to be the new video type. The code appears to work fine but my code outputs a different order and and I am not sure why.

When I process the code with my Java code the JSON the output looks like this:

    {
    "TransformType": {
        "encodeOptions": [
            {
                "types": [
                    "MPEG"
                ],
                "title": "Convert to MPEG"
            }
        ],
        "processType": "encode"
    }
}

The output that system is expecting looks like this:

{
    "TransformType": {
        "processType": "encode",
        "encodeOptions": [
            {
                "types": [
                    "MPEG"
                ],
                "title": "Convert to MPEG"
            }
        ]
    }
}

My code is very simple:

HashMap<String,String> newTypesMap = new HashMap<String,String>();


    if (TransformTypeObj.has("encodeOptions")) {

        JSONArray encodingOptionsArr = TransformTypeObj.getJSONArray("encodeOptions");

        for( int i = 0; i < encodingOptionsArr.length(); i++ ) {

             JSONObject encodeOptObj = encodeOptionsArray.getJSONObject(i); 
             JSONArray typesArr = encodeOptObj.getJSONArray("types");

             for (int h = 0; h < typesArr.length(); h++) {
                    String oldtype = typesArr.getString(h).toString();
                    String newType = newTypesMap.get(oldtype);
                    typesArr.put(h, newType);
            }
         } 
    }

I cannot edit or see into this third party system but apparently order is important. I edited my Java output into the 'correct' format and did a manual post and the system accepts it. If I attempt to use my java code output I get an error saying:

Java.lang.RuntimeException: com.jacksonmedia.data.api.marshalling.MarshallingException: array element type mismatch

Which I assume has something to do with the order of the objects. How can I make the 'processType' JSONString be the first element in the TransformType object??

Upvotes: 0

Views: 1071

Answers (2)

Steve Kuo
Steve Kuo

Reputation: 63114

Instead of HashMap use LinkedHashMap which preserves the insertion order.

Upvotes: 3

jtahlborn
jtahlborn

Reputation: 53694

I assume you are using the JSONObject impl from json.org. unfortunately, the JSONObject does not preserve the order of the internal elements (it uses a HashMap internally). You could find another JSON library which preserves order. Alternately, you could get the source and change JSONObject to use a LinkedHashMap internally and use your custom implementation instead.

Upvotes: 1

Related Questions