Quantcast
Channel: JSON order mixed up - Stack Overflow
Viewing all articles
Browse latest Browse all 18

Answer by t3az0r for JSON order mixed up

$
0
0

I found a "neat" reflection tweak on "the interwebs" that I like to share.(origin: https://towardsdatascience.com/create-an-ordered-jsonobject-in-java-fb9629247d76)

It is about to change underlying collection in org.json.JSONObject to an un-ordering one (LinkedHashMap) by reflection API.

I tested succesfully:

import java.lang.reflect.Field;import java.util.LinkedHashMap;import org.json.JSONObject;private static void makeJSONObjLinear(JSONObject jsonObject) {    try {            Field changeMap = jsonObject.getClass().getDeclaredField("map");            changeMap.setAccessible(true);            changeMap.set(jsonObject, new LinkedHashMap<>());            changeMap.setAccessible(false);        } catch (IllegalAccessException | NoSuchFieldException e) {            e.printStackTrace();        }}[...]JSONObject requestBody = new JSONObject();makeJSONObjLinear(requestBody);requestBody.put("username", login);requestBody.put("password", password);[...]// returned   '{"username": "billy_778", "password": "********"}' == unordered// instead of '{"password": "********", "username": "billy_778"}' == ordered (by key)

Viewing all articles
Browse latest Browse all 18

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>