print members of map in defined order
This commit is contained in:
parent
bf28f2a755
commit
1b01d43a61
@ -1,14 +1,15 @@
|
|||||||
package de.hsadmin.jscli.json;
|
package de.hsadmin.jscli.json;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
public class JSONFormatter {
|
public class JSONFormatter {
|
||||||
|
|
||||||
private int indent = 1;
|
private int indent = 1;
|
||||||
|
|
||||||
public String format(Object object) {
|
public String format(final Object object) {
|
||||||
if (object == null) return "";
|
if (object == null) return "";
|
||||||
if (object instanceof List<?>) {
|
if (object instanceof List<?>) {
|
||||||
return formatList((List<?>) object);
|
return formatList((List<?>) object);
|
||||||
@ -25,14 +26,15 @@ public class JSONFormatter {
|
|||||||
return "an instance of " + object.getClass().getCanonicalName();
|
return "an instance of " + object.getClass().getCanonicalName();
|
||||||
}
|
}
|
||||||
|
|
||||||
public String formatMap(Map<?, ?> map) {
|
public String formatMap(final Map<?, ?> map) {
|
||||||
StringBuffer result = new StringBuffer();
|
final StringBuffer result = new StringBuffer();
|
||||||
result.append('{');
|
result.append('{');
|
||||||
incr();
|
incr();
|
||||||
result.append(newline());
|
result.append(newline());
|
||||||
StringBuffer formattedMap = new StringBuffer();
|
final StringBuffer formattedMap = new StringBuffer();
|
||||||
Set<?> keySet = map.keySet();
|
final List<String> listOfKeys = Arrays.asList(map.keySet().toArray(new String[] {}));
|
||||||
for (Object key : keySet) {
|
Collections.sort(listOfKeys);
|
||||||
|
for (final Object key : listOfKeys) {
|
||||||
if (formattedMap.length() > 0) {
|
if (formattedMap.length() > 0) {
|
||||||
formattedMap.append(',');
|
formattedMap.append(',');
|
||||||
formattedMap.append(newline());
|
formattedMap.append(newline());
|
||||||
@ -48,15 +50,15 @@ public class JSONFormatter {
|
|||||||
return result.toString();
|
return result.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
public String formatString(String str) {
|
public String formatString(final String str) {
|
||||||
return "'" + str + "'";
|
return "'" + str + "'";
|
||||||
}
|
}
|
||||||
|
|
||||||
public String formatList(List<?> list) {
|
public String formatList(final List<?> list) {
|
||||||
return formatArr(list.toArray());
|
return formatArr(list.toArray());
|
||||||
}
|
}
|
||||||
|
|
||||||
public String formatArr(Object[] arr) {
|
public String formatArr(final Object[] arr) {
|
||||||
StringBuffer result = new StringBuffer();
|
StringBuffer result = new StringBuffer();
|
||||||
result.append('[');
|
result.append('[');
|
||||||
incr();
|
incr();
|
||||||
|
Loading…
Reference in New Issue
Block a user