Add feature to SimpleJsonParser

Now it can parse nested lists as map values.

Fixes gh-169
pull/172/head
Dave Syer 11 years ago
parent bddf624bcb
commit 1194fc882b

@ -110,12 +110,7 @@ public class SimpleJsonParser implements JsonParser {
if (values.length > 0) { if (values.length > 0) {
String string = trimLeadingCharacter( String string = trimLeadingCharacter(
trimTrailingCharacter(values[1], '"'), '"'); trimTrailingCharacter(values[1], '"'), '"');
if (string.startsWith("{") && string.endsWith("}")) { value = parseInternal(string);
value = parseInternal(string);
}
else {
value = string;
}
} }
map.put(key, value); map.put(key, value);
} }
@ -126,6 +121,7 @@ public class SimpleJsonParser implements JsonParser {
List<String> list = new ArrayList<String>(); List<String> list = new ArrayList<String>();
int index = 0; int index = 0;
int inObject = 0; int inObject = 0;
int inList = 0;
StringBuilder build = new StringBuilder(); StringBuilder build = new StringBuilder();
while (index < json.length()) { while (index < json.length()) {
char current = json.charAt(index); char current = json.charAt(index);
@ -135,7 +131,13 @@ public class SimpleJsonParser implements JsonParser {
if (current == '}') { if (current == '}') {
inObject--; inObject--;
} }
if (current == ',' && inObject == 0) { if (current == '[') {
inList++;
}
if (current == ']') {
inList--;
}
if (current == ',' && inObject == 0 && inList == 0) {
list.add(build.toString()); list.add(build.toString());
build.setLength(0); build.setLength(0);
} }

@ -20,8 +20,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import org.junit.Test; import org.junit.Test;
import org.springframework.boot.config.JsonParser;
import org.springframework.boot.config.SimpleJsonParser;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@ -74,4 +72,13 @@ public class SimpleJsonParserTests {
assertEquals(2, ((Map<String, Object>) list.get(1)).size()); assertEquals(2, ((Map<String, Object>) list.get(1)).size());
} }
@SuppressWarnings("unchecked")
@Test
public void testMapOfLists() {
Map<String, Object> map = this.parser
.parseMap("{\"foo\":[{\"foo\":\"bar\",\"spam\":1},{\"foo\":\"baz\",\"spam\":2}]}");
assertEquals(1, map.size());
assertEquals(2, ((List<Object>) map.get("foo")).size());
}
} }

Loading…
Cancel
Save