Skip to content

Commit 333b426

Browse files
committed
toJson has higher priority than toMap/asMap when converting to JSON
1 parent a19f161 commit 333b426

File tree

2 files changed

+34
-12
lines changed

2 files changed

+34
-12
lines changed

java/client/src/org/openqa/selenium/remote/BeanToJsonConverter.java

+12-12
Original file line numberDiff line numberDiff line change
@@ -179,18 +179,6 @@ private JsonElement convertObject(Object toConvert, int maxDepth) throws Excepti
179179
return new JsonPrimitive(((File) toConvert).getAbsolutePath());
180180
}
181181

182-
Method toMap = getMethod(toConvert, "toMap");
183-
if (toMap == null) {
184-
toMap = getMethod(toConvert, "asMap");
185-
}
186-
if (toMap != null) {
187-
try {
188-
return convertObject(toMap.invoke(toConvert), maxDepth - 1);
189-
} catch (ReflectiveOperationException e) {
190-
throw new WebDriverException(e);
191-
}
192-
}
193-
194182
Method toJson = getMethod(toConvert, "toJson");
195183
if (toJson != null) {
196184
try {
@@ -215,6 +203,18 @@ private JsonElement convertObject(Object toConvert, int maxDepth) throws Excepti
215203
}
216204
}
217205

206+
Method toMap = getMethod(toConvert, "toMap");
207+
if (toMap == null) {
208+
toMap = getMethod(toConvert, "asMap");
209+
}
210+
if (toMap != null) {
211+
try {
212+
return convertObject(toMap.invoke(toConvert), maxDepth - 1);
213+
} catch (ReflectiveOperationException e) {
214+
throw new WebDriverException(e);
215+
}
216+
}
217+
218218
try {
219219
return mapObject(toConvert, maxDepth - 1, toConvert instanceof Cookie);
220220
} catch (Exception e) {

java/client/test/org/openqa/selenium/remote/BeanToJsonConverterTest.java

+22
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,12 @@ public void testShouldCallToJsonMethodIfPresent() {
235235
assertEquals("\"converted\"", json);
236236
}
237237

238+
@Test
239+
public void testShouldPreferToJsonMethodToToMapMethod() {
240+
String json = new BeanToJsonConverter().convert(new MappableJsonAware("converted"));
241+
assertEquals("\"converted\"", json);
242+
}
243+
238244
@Test
239245
public void toJsonMethodCanConvertibleReturnedMap() {
240246
class ToJsonReturnsMap {
@@ -586,6 +592,22 @@ public String toJson() {
586592
}
587593
}
588594

595+
public class MappableJsonAware {
596+
private String convertedValue;
597+
598+
public MappableJsonAware(String convertedValue) {
599+
this.convertedValue = convertedValue;
600+
}
601+
602+
public String toJson() {
603+
return convertedValue;
604+
}
605+
606+
public Map<String, Object> asMap() {
607+
return ImmutableMap.of("key", "value");
608+
}
609+
}
610+
589611
public class Mappable1 {
590612
private String key;
591613
private Object value;

0 commit comments

Comments
 (0)