001
014
015 package com.liferay.portal.kernel.json;
016
017 import com.liferay.portal.kernel.util.ReflectionUtil;
018
019 import java.util.ArrayList;
020 import java.util.Collections;
021 import java.util.Comparator;
022 import java.util.Iterator;
023 import java.util.List;
024
025 import org.json.JSONException;
026
027
030 public class JSONObjectUtil {
031
032 public static String toOrderedJSONString(JSONObject jsonObject) {
033 return toOrderedJSONString(jsonObject.toString());
034 }
035
036 public static String toOrderedJSONString(String jsonString) {
037 try {
038 org.json.JSONObject jsonObject =
039 new org.json.JSONObject(jsonString) {
040
041 @Override
042 @SuppressWarnings("rawtypes")
043 public Iterator keys() {
044 Iterator<?> iterator = super.keys();
045
046 List<Object> list = new ArrayList<>(length());
047
048 while (iterator.hasNext()) {
049 list.add(iterator.next());
050 }
051
052 Collections.sort(
053 list,
054 new Comparator<Object>() {
055
056 @Override
057 public int compare(
058 Object object1, Object object2) {
059
060 String string1 = object1.toString();
061
062 return string1.compareTo(
063 object2.toString());
064 }
065
066 });
067
068 return list.iterator();
069 }
070
071 };
072
073 return jsonObject.toString();
074 }
075 catch (JSONException jsone) {
076 return ReflectionUtil.throwException(jsone);
077 }
078 }
079
080 }