修改Json#node方法,改为返回List<Json>,方便链式调用

pull/835/head
xukeek 7 years ago
parent be892b80bf
commit ac03b903eb

@ -3,6 +3,7 @@ package us.codecraft.webmagic.selector;
import com.alibaba.fastjson.JSON;
import us.codecraft.xsoup.XTokenQueue;
import java.util.ArrayList;
import java.util.List;
/**
@ -52,6 +53,20 @@ public class Json extends PlainText {
@Override
public Selectable jsonPath(String jsonPath) {
JsonPathSelector jsonPathSelector = new JsonPathSelector(jsonPath);
return selectList(jsonPathSelector,getSourceTexts());
List<String> results = new ArrayList<String>();
for (String string : getSourceTexts()) {
List<String> result = jsonPathSelector.selectList(string);
results.addAll(result);
}
return new Json(results);
}
@Override
public List<Selectable> nodes() {
List<Selectable> nodes = new ArrayList<Selectable>(getSourceTexts().size());
for (String string : getSourceTexts()) {
nodes.add(new Json(string));
}
return nodes;
}
}

@ -14,6 +14,8 @@ public class JsonTest {
private String textWithBrackerInContent = "callback({\"name\":\"json)\"})";
private String textChained = "callback({\"provinces\": [{cities: [{\"name\": \"shanghai\"}]}]})";
@Test
public void testRemovePadding() throws Exception {
String name = new Json(text).removePadding("callback").jsonPath("$.name").get();
@ -25,4 +27,11 @@ public class JsonTest {
String name = new Json(textWithBrackerInContent).removePadding("callback").jsonPath("$.name").get();
assertThat(name).isEqualTo("json)");
}
@Test
public void testChainCall() throws Exception {
String shanghai = new Json(textChained).removePadding("callback").jsonPath("$.provinces").nodes().get(0)
.jsonPath("$.cities").nodes().get(0).jsonPath("$.name").get();
assertThat(shanghai).isEqualTo("shanghai");
}
}

Loading…
Cancel
Save