Skip to content

Commit 01c4f9f

Browse files
committed
java: Convert an object to JSON with the help of asList/toList method if available
1 parent 6cfa491 commit 01c4f9f

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

Diff for: java/client/src/org/openqa/selenium/remote/BeanToJsonConverter.java

+16
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,22 @@ private JsonElement convertObject(Object toConvert, int maxDepth) throws Excepti
192192
}
193193
}
194194

195+
Method toList = getMethod(toConvert, "toList");
196+
if (toList == null) {
197+
toList = getMethod(toConvert, "asList");
198+
}
199+
if (toList != null) {
200+
try {
201+
return convertObject(toList.invoke(toConvert), maxDepth - 1);
202+
} catch (IllegalArgumentException e) {
203+
throw new WebDriverException(e);
204+
} catch (IllegalAccessException e) {
205+
throw new WebDriverException(e);
206+
} catch (InvocationTargetException e) {
207+
throw new WebDriverException(e);
208+
}
209+
}
210+
195211
Method toJson = getMethod(toConvert, "toJson");
196212
if (toJson != null) {
197213
try {

Diff for: java/client/test/org/openqa/selenium/remote/BeanToJsonConverterTest.java

+38
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
package org.openqa.selenium.remote;
1919

20+
import com.google.common.collect.ImmutableList;
2021
import com.google.common.collect.ImmutableMap;
2122
import com.google.common.collect.Lists;
2223
import com.google.common.collect.Maps;
@@ -242,6 +243,18 @@ public void testShouldCallToMapMethodIfPresent() {
242243
assertEquals("{\"a key\":\"a value\"}", json);
243244
}
244245

246+
@Test
247+
public void testShouldCallAsListMethodIfPresent() {
248+
String json = new BeanToJsonConverter().convert(new Listable1("item1", "item2"));
249+
assertEquals("[\"item1\",\"item2\"]", json);
250+
}
251+
252+
@Test
253+
public void testShouldCallToListMethodIfPresent() {
254+
String json = new BeanToJsonConverter().convert(new Listable2("item1", "item2"));
255+
assertEquals("[\"item1\",\"item2\"]", json);
256+
}
257+
245258
@Test
246259
public void testConvertsToJsonMethodResultToPrimitiveIfItIsNotJson() {
247260
// We want this parsed as a string primitive, but JsonParser will reject it
@@ -562,4 +575,29 @@ public Map<String, Object> toMap() {
562575
return ImmutableMap.of(key, value);
563576
}
564577
}
578+
579+
public class Listable1 {
580+
private List<String> items;
581+
582+
public Listable1(String... items) {
583+
this.items = ImmutableList.copyOf(items);
584+
}
585+
586+
public List<String> asList() {
587+
return items;
588+
}
589+
}
590+
591+
public class Listable2 {
592+
private List<String> items;
593+
594+
public Listable2(String... items) {
595+
this.items = ImmutableList.copyOf(items);
596+
}
597+
598+
public List<String> toList() {
599+
return items;
600+
}
601+
}
602+
565603
}

0 commit comments

Comments
 (0)