PageRenderTime 52ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/webmagic-core/src/main/java/us/codecraft/webmagic/selector/Json.java

https://gitlab.com/taichu/webmagic
Java | 57 lines | 38 code | 9 blank | 10 comment | 4 complexity | c342eaafcfbfa259225d56f9cf586775 MD5 | raw file
  1. package us.codecraft.webmagic.selector;
  2. import com.alibaba.fastjson.JSON;
  3. import us.codecraft.xsoup.XTokenQueue;
  4. import java.util.List;
  5. /**
  6. * parse json
  7. * @author code4crafter@gmail.com
  8. * @since 0.5.0
  9. */
  10. public class Json extends PlainText {
  11. public Json(List<String> strings) {
  12. super(strings);
  13. }
  14. public Json(String text) {
  15. super(text);
  16. }
  17. /**
  18. * remove padding for JSONP
  19. * @param padding padding
  20. * @return json after padding removed
  21. */
  22. public Json removePadding(String padding) {
  23. String text = getFirstSourceText();
  24. XTokenQueue tokenQueue = new XTokenQueue(text);
  25. tokenQueue.consumeWhitespace();
  26. tokenQueue.consume(padding);
  27. tokenQueue.consumeWhitespace();
  28. String chompBalanced = tokenQueue.chompBalancedNotInQuotes('(', ')');
  29. return new Json(chompBalanced);
  30. }
  31. public <T> T toObject(Class<T> clazz) {
  32. if (getFirstSourceText() == null) {
  33. return null;
  34. }
  35. return JSON.parseObject(getFirstSourceText(), clazz);
  36. }
  37. public <T> List<T> toList(Class<T> clazz) {
  38. if (getFirstSourceText() == null) {
  39. return null;
  40. }
  41. return JSON.parseArray(getFirstSourceText(), clazz);
  42. }
  43. @Override
  44. public Selectable jsonPath(String jsonPath) {
  45. JsonPathSelector jsonPathSelector = new JsonPathSelector(jsonPath);
  46. return selectList(jsonPathSelector,getSourceTexts());
  47. }
  48. }