us.codecraft.webmagic.selector.Json Maven / Gradle / Ivy
The newest version!
package us.codecraft.webmagic.selector;
import com.alibaba.fastjson.JSON;
import us.codecraft.xsoup.XTokenQueue;
import java.util.List;
/**
* parse json
* @author [email protected]
* @since 0.5.0
*/
public class Json extends PlainText {
public Json(List strings) {
super(strings);
}
public Json(String text) {
super(text);
}
/**
* remove padding for JSONP
* @param padding padding
* @return json after padding removed
*/
public Json removePadding(String padding) {
String text = getFirstSourceText();
XTokenQueue tokenQueue = new XTokenQueue(text);
tokenQueue.consumeWhitespace();
tokenQueue.consume(padding);
tokenQueue.consumeWhitespace();
String chompBalanced = tokenQueue.chompBalancedNotInQuotes('(', ')');
return new Json(chompBalanced);
}
public T toObject(Class clazz) {
if (getFirstSourceText() == null) {
return null;
}
return JSON.parseObject(getFirstSourceText(), clazz);
}
public List toList(Class clazz) {
if (getFirstSourceText() == null) {
return null;
}
return JSON.parseArray(getFirstSourceText(), clazz);
}
@Override
public Selectable jsonPath(String jsonPath) {
JsonPathSelector jsonPathSelector = new JsonPathSelector(jsonPath);
return selectList(jsonPathSelector,getSourceTexts());
}
}