Skip to content

Commit

Permalink
toJson has higher priority than toMap/asMap when converting to JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
barancev committed Aug 30, 2017
1 parent a19f161 commit 333b426
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 12 deletions.
24 changes: 12 additions & 12 deletions java/client/src/org/openqa/selenium/remote/BeanToJsonConverter.java
Original file line number Diff line number Diff line change
Expand Up @@ -179,18 +179,6 @@ private JsonElement convertObject(Object toConvert, int maxDepth) throws Excepti
return new JsonPrimitive(((File) toConvert).getAbsolutePath());
}

Method toMap = getMethod(toConvert, "toMap");
if (toMap == null) {
toMap = getMethod(toConvert, "asMap");
}
if (toMap != null) {
try {
return convertObject(toMap.invoke(toConvert), maxDepth - 1);
} catch (ReflectiveOperationException e) {
throw new WebDriverException(e);
}
}

Method toJson = getMethod(toConvert, "toJson");
if (toJson != null) {
try {
Expand All @@ -215,6 +203,18 @@ private JsonElement convertObject(Object toConvert, int maxDepth) throws Excepti
}
}

Method toMap = getMethod(toConvert, "toMap");
if (toMap == null) {
toMap = getMethod(toConvert, "asMap");
}
if (toMap != null) {
try {
return convertObject(toMap.invoke(toConvert), maxDepth - 1);
} catch (ReflectiveOperationException e) {
throw new WebDriverException(e);
}
}

try {
return mapObject(toConvert, maxDepth - 1, toConvert instanceof Cookie);
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,12 @@ public void testShouldCallToJsonMethodIfPresent() {
assertEquals("\"converted\"", json);
}

@Test
public void testShouldPreferToJsonMethodToToMapMethod() {
String json = new BeanToJsonConverter().convert(new MappableJsonAware("converted"));
assertEquals("\"converted\"", json);
}

@Test
public void toJsonMethodCanConvertibleReturnedMap() {
class ToJsonReturnsMap {
Expand Down Expand Up @@ -586,6 +592,22 @@ public String toJson() {
}
}

public class MappableJsonAware {
private String convertedValue;

public MappableJsonAware(String convertedValue) {
this.convertedValue = convertedValue;
}

public String toJson() {
return convertedValue;
}

public Map<String, Object> asMap() {
return ImmutableMap.of("key", "value");
}
}

public class Mappable1 {
private String key;
private Object value;
Expand Down

0 comments on commit 333b426

Please sign in to comment.