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