Skip to content

Add a helper method to parse maps of objects #53096

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@
import org.elasticsearch.common.xcontent.XContentParser.Token;

import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Supplier;

Expand Down Expand Up @@ -159,4 +161,36 @@ public static <T> void parseTypedKeysObject(XContentParser parser, String delimi
throw new ParsingException(parser.getTokenLocation(), "Failed to parse object: empty key");
}
}

/**
* Parses a json map of objects into a map
*
* Each map key is passed as the context to the object parser used to construct
* the map values.
*
* @param p the XContentParser
* @param objectParser a parser used to construct map values
* @param singleton if {@code true}, then an exception is thrown if the map has more than one key
*/
public static <T> Map<String, T> parseMap(XContentParser p, ContextParser<String, T> objectParser,
boolean singleton) throws IOException {
Map<String, T> map = new HashMap<>();
if (p.currentToken() != Token.START_OBJECT) {
ensureExpectedToken(Token.START_OBJECT, p.nextToken(), p::getTokenLocation);
}
while (p.nextToken() != XContentParser.Token.END_OBJECT) {
ensureExpectedToken(Token.FIELD_NAME, p.currentToken(), p::getTokenLocation);
if (singleton && map.isEmpty() == false) {
throw new XContentParseException(p.getTokenLocation(),
"Expected a single field but found [" + map.keySet().iterator().next() + "," + p.currentName() + "]");
}
String currentField = p.currentName();
try {
map.put(currentField, objectParser.parse(p, currentField));
} catch (Exception e) {
throw new XContentParseException(p.getTokenLocation(), "Error parsing field [" + currentField + "]", e);
}
}
return map;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@
import static org.elasticsearch.common.xcontent.XContentParserUtils.parseTypedKeysObject;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.instanceOf;

public class XContentParserUtilsTests extends ESTestCase {
Expand Down Expand Up @@ -253,4 +255,61 @@ public void testParseTypedKeysObjectErrors() throws IOException {
}
}
}

private static class TestStruct {
final String name;
String a;
long b;

TestStruct(String name) {
this.name = name;
}
}

public void testMapParsing() throws IOException {

ObjectParser<TestStruct, String> structParser = ObjectParser.fromBuilder("test", TestStruct::new);
structParser.declareString((t, s) -> t.a = s, new ParseField("a"));
structParser.declareLong((t, l) -> t.b = l, new ParseField("b"));

XContentParser parser = createParser(JsonXContent.jsonXContent,
"{ \"label1\" : { \"a\" : \"hello\", \"b\" : 1 }, \"label2\" : { \"a\" : \"world\", \"b\" : 2 } }");

Map<String, TestStruct> map = XContentParserUtils.parseMap(parser, structParser, false);

assertThat(map, hasKey("label1"));
assertThat(map.get("label1").name, equalTo("label1"));
assertThat(map.get("label1").a, equalTo("hello"));
assertThat(map.get("label1").b, equalTo(1L));
assertThat(map, hasKey("label2"));
assertThat(map.get("label2").name, equalTo("label2"));
assertThat(map.get("label2").a, equalTo("world"));
assertThat(map.get("label2").b, equalTo(2L));

}

public void testMapParsingErrors() throws IOException {

ObjectParser<TestStruct, String> structParser = ObjectParser.fromBuilder("test", TestStruct::new);
structParser.declareString((t, s) -> t.a = s, new ParseField("a"));
structParser.declareLong((t, l) -> t.b = l, new ParseField("b"));

{
XContentParser parser = createParser(JsonXContent.jsonXContent,
"{ \"label1\" : { \"a\" : \"hello\", \"b\" : 1 }, \"label2\" : { \"a\" : \"world\", \"b\" : 2 } }");
Exception e = expectThrows(XContentParseException.class, () -> XContentParserUtils.parseMap(parser, structParser, true));
assertThat(e.getMessage(), equalTo("[1:42] Expected a single field but found [label1,label2]"));
}

{
XContentParser parser = createParser(JsonXContent.jsonXContent,
"{ \"label1\" : { \"a\" : \"hello\", \"b\" : 1 }, \"label2\" : { \"a\" : \"world\", \"b\" : \"two\" } }");
Exception e = expectThrows(XContentParseException.class, () -> XContentParserUtils.parseMap(parser, structParser, false));
assertThat(e.getMessage(), equalTo("[1:76] Error parsing field [label2]"));
Throwable t = e.getCause();
assertNotNull(t);
assertThat(t.getMessage(), containsString("[test] failed to parse field [b]"));
}

}
}