PageRenderTime 33ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/webmagic-core/src/test/java/us/codecraft/webmagic/selector/JsonPathSelectorTest.java

https://gitlab.com/taichu/webmagic
Java | 55 lines | 46 code | 6 blank | 3 comment | 0 complexity | c7ce9114d87102b71e9145664ebe7b99 MD5 | raw file
  1. package us.codecraft.webmagic.selector;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import org.junit.Test;
  5. import java.util.List;
  6. import static org.assertj.core.api.Assertions.assertThat;
  7. /**
  8. * @author code4crafter@gmai.com <br>
  9. */
  10. public class JsonPathSelectorTest {
  11. private String text = "{ \"store\": {\n" +
  12. " \"book\": [ \n" +
  13. " { \"category\": \"reference\",\n" +
  14. " \"author\": \"Nigel Rees\",\n" +
  15. " \"title\": \"Sayings of the Century\",\n" +
  16. " \"price\": 8.95\n" +
  17. " },\n" +
  18. " { \"category\": \"fiction\",\n" +
  19. " \"author\": \"Evelyn Waugh\",\n" +
  20. " \"title\": \"Sword of Honour\",\n" +
  21. " \"price\": 12.99,\n" +
  22. " \"isbn\": \"0-553-21311-3\"\n" +
  23. " }\n" +
  24. " ],\n" +
  25. " \"bicycle\": {\n" +
  26. " \"color\": \"red\",\n" +
  27. " \"price\": 19.95\n" +
  28. " }\n" +
  29. " }\n" +
  30. "}";
  31. @Test
  32. public void testJsonPath() {
  33. JsonPathSelector jsonPathSelector = new JsonPathSelector("$.store.book[*].author");
  34. String select = jsonPathSelector.select(text);
  35. List<String> list = jsonPathSelector.selectList(text);
  36. assertThat(select).isEqualTo("Nigel Rees");
  37. assertThat(list).contains("Nigel Rees","Evelyn Waugh");
  38. jsonPathSelector = new JsonPathSelector("$.store.book[?(@.category == 'reference')].title");
  39. list = jsonPathSelector.selectList(text);
  40. select = jsonPathSelector.select(text);
  41. assertThat(select).isEqualTo("Sayings of the Century");
  42. assertThat(list).contains("Sayings of the Century");
  43. jsonPathSelector = new JsonPathSelector("$.store.book[?(@.category == 'reference')]");
  44. select = jsonPathSelector.select(text);
  45. JSONObject object1= JSON.parseObject(select);
  46. JSONObject object2=JSON.parseObject("{\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"category\":\"reference\",\"price\":8.95}");
  47. assertThat(object1).isEqualTo(object2);
  48. }
  49. }