下面列出了com.alibaba.fastjson.JSONArray#getString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void initBackgroundColor(Object obj) {
if (obj == null)
return;
if (obj instanceof JSONObject) {
mBackgroundColor = new BackgroundColorCreator();
JSONObject object = (JSONObject) obj;
JSONArray in = object.getJSONArray("in");
mBackgroundColor.input = new int[in.size()];
for (int i = 0; i < in.size(); i++) {
mBackgroundColor.input[i] = in.getInteger(i);
}
JSONArray out = object.getJSONArray("out");
mBackgroundColor.output = new int[out.size()];
for (int i = 0; i < out.size(); i++) {
String colorStr = out.getString(i);
mBackgroundColor.output[i] = WXResourceUtils.getColor(colorStr);
}
}
}
/**
* 解析 精度
*
* @param result 原始信息
* @return 解析结果
*/
public static Precisions parsePrecisions(String result) {
JSONObject r = JSON.parseObject(result);
if (OK.equals(r.getString(STATUS))) {
JSONArray data = r.getJSONArray(DATA);
List<Precision> precisions = new ArrayList<>(data.size());
for (int i = 0; i < data.size(); i++) {
JSONObject t = data.getJSONObject(i);
String symbol = t.getString("base-currency") + "_" + t.getString("quote-currency");
symbol = symbol.toUpperCase();
Integer base = t.getInteger("amount-precision");
Integer count = t.getInteger("price-precision");
Precision precision = new Precision(data.getString(i), symbol,
base, count,
null, null,
null, null,
null, null);
precisions.add(precision);
}
return new Precisions(precisions);
}
return null;
}
/**
* 获取相关人员(提交人/审批人/抄送人)
*
* @param operator
* @param record
* @return
*/
public Set<ID> getSpecUsers(ID operator, ID record) {
JSONArray userDefs = getDataMap().getJSONArray("users");
if (userDefs == null || userDefs.isEmpty()) {
return Collections.emptySet();
}
String userType = userDefs.getString(0);
if (USER_SELF.equalsIgnoreCase(userType)) {
Set<ID> users = new HashSet<>();
ID owning = Application.getRecordOwningCache().getOwningUser(record);
users.add(owning);
return users;
}
List<String> defsList = new ArrayList<>();
for (Object o : userDefs) {
defsList.add((String) o);
}
return UserHelper.parseUsers(defsList, null);
}
/**
* @param jsonStr
* @param changeType 0加密 or 1解密
* @return jsonStr
*/
public static String changeJson(String jsonStr, Integer changeType) {
JSONObject json = JSONObject.parseObject(jsonStr);
JSONObject job = json.getJSONObject("job");
JSONArray contents = job.getJSONArray("content");
for (int i = 0; i < contents.size(); i++) {
String contentStr = contents.getString(i);
Object obj = contents.get(i);
if (decrypt.equals(changeType)) { //解密
((JSONObject) obj).put("reader", change(contentStr, "reader", decrypt));
((JSONObject) obj).put("writer", change(contentStr, "writer", decrypt));
} else if (encrypt.equals(changeType)) {//加密
((JSONObject) obj).put("reader", change(contentStr, "reader", encrypt));
((JSONObject) obj).put("writer", change(contentStr, "writer", encrypt));
}
}
job.put("content", contents);
json.put("job", job);
return json.toJSONString();
}
/**
* 创建试题标签.
* @param problemId - 试题的唯一标识符
* @param problemTags - 试题标签的JSON数组
*/
private void createProblemTags(long problemId, String problemTags) {
Set<String> problemTagSlugs = new HashSet<>();
JSONArray jsonArray = JSON.parseArray(problemTags);
for ( int i = 0; i < jsonArray.size(); ++ i ) {
String problemTagName = jsonArray.getString(i);
String problemTagSlug = SlugifyUtils.getSlug(problemTagName);
ProblemTag pt = problemTagMapper.getProblemTagUsingTagSlug(problemTagSlug);
if ( pt == null ) {
pt = new ProblemTag(problemTagSlug, problemTagName);
problemTagMapper.createProblemTag(pt);
}
// Fix Bug: Two tags have different tag name but the same tag slug.
// Example: Hello World / Hello-World
if ( !problemTagSlugs.contains(problemTagSlug) ) {
problemTagMapper.createProblemTagRelationship(problemId, pt);
problemTagSlugs.add(problemTagSlug);
}
}
}
/**
* 认证
*
* @param messageInfo
*/
private void identify(IHttpRequestResponse messageInfo) {
String host = messageInfo.getHttpService().getHost();
if(AC_SERVER.contains(host)){ // 认证站点
IRequestInfo requestInfo = this.callbacks.getHelpers().analyzeRequest(messageInfo.getRequest());
if (requestInfo.getHeaders().get(0).contains("/api/identify")) { // 从这个路径下获取认证信息
IResponseInfo responseInfo = this.callbacks.getHelpers().analyzeResponse(messageInfo.getResponse());
if (responseInfo.getStatusCode() == 200) {
String body = new String(messageInfo.getResponse(), responseInfo.getBodyOffset(),
messageInfo.getResponse().length - responseInfo.getBodyOffset());
JSONObject jsonObject = JSON.parseObject(body);
if (!"success".equals(jsonObject.getString("flag"))) {
STDERR.println("认证失败: " + jsonObject.get("data").toString());
} else {
JSONArray datas = jsonObject.getJSONArray("data");
if (datas.size() != 2) {
STDERR.println("认证异常!");
} else {
UNIQUE_NAME = datas.getString(0);
UNIQUE_UID = datas.getString(1);
STDOUT.println(String.format("%s login ...", UNIQUE_NAME));
jPanelMain.setNameLabel(String.format("你好:%s", UNIQUE_NAME));
// 认证成功后,重定向到主页
messageInfo.setResponse(genRedirectACSite());
}
}
}
}
} else if (!Utils.identifyWriteList(host)) {
messageInfo.setResponse(genRedirectAC()); // 不在白名单内重定向到AC
}
}
@Override
protected Accountable createValue(final AtomicReader reader, CacheKey key, boolean setDocsWithField)
throws IOException {
int maxDoc = reader.maxDoc();
final String[][] matrix = new String[maxDoc][];
BinaryDocValues valuesIn = reader.getBinaryDocValues(key.field);
if (valuesIn == null) {
for (int i = 0; i < maxDoc; ++i) {
matrix[i] = new String[0];
}
return new StringList(matrix);
}
for (int i = 0; i < maxDoc; ++i) {
String str = valuesIn.get(i).utf8ToString();
if (StringUtils.isEmpty(str)) {
matrix[i] = new String[0];
continue;
}
JSONArray array = JSON.parseArray(str);
matrix[i] = new String[array.size()];
for (int j = 0; j < array.size(); ++j) {
matrix[i][j] = array.getString(j);
}
}
return new StringList(matrix);
}
/**
* 创建试题所属分类.
* @param problemId - 试题的唯一标识符
* @param problemCategories - 试题分类别名的JSON数组
*/
private void createProblemCategoryRelationships(long problemId, String problemCategories) {
JSONArray jsonArray = JSON.parseArray(problemCategories);
if ( jsonArray.size() == 0 ) {
jsonArray.add("uncategorized");
}
for ( int i = 0; i < jsonArray.size(); ++ i ) {
String problemCategorySlug = jsonArray.getString(i);
ProblemCategory pc = problemCategoryMapper.getProblemCategoryUsingCategorySlug(problemCategorySlug);
problemCategoryMapper.createProblemCategoryRelationship(problemId, pc);
}
}
@Override
public String[] getAsStringArray(JSONObject json, String key) {
if (json == null || validator.isEmpty(key) || !json.containsKey(key))
return new String[0];
JSONArray array = json.getJSONArray(key);
String[] strings = new String[array.size()];
for (int i = 0; i < strings.length; i++)
strings[i] = array.getString(i);
return strings;
}
static Precision of(JSONArray r) {
return new Precision(
Util.decode(r.getString(0)),
r.getString(1),
r.getInteger(2),
r.getInteger(3),
r.getBigDecimal(4),
r.getBigDecimal(5),
r.getBigDecimal(6),
r.getBigDecimal(7),
r.getBigDecimal(8),
r.getBigDecimal(9));
}
static Order of(JSONArray r) {
return new Order(
Util.decode(r.getString(0)),
r.getLong(1),
r.getString(2),
Util.of(r.getString(3), Side::valueOf),
Util.of(r.getString(4), Type::valueOf),
Util.of(r.getString(5), State::valueOf),
r.getBigDecimal(6),
r.getBigDecimal(7),
r.getBigDecimal(8),
r.getBigDecimal(9));
}
static OrderDetail of(JSONArray r) {
return new OrderDetail
(Util.decode(r.getString(0)),
r.getLong(1),
r.getString(2),
r.getString(3),
r.getBigDecimal(4),
r.getBigDecimal(5),
r.getBigDecimal(6),
r.getString(7),
Util.of(r.getString(8), Side::valueOf));
}
static Balance of(JSONArray r) {
return new Balance(
Util.decode(r.getString(0)),
r.getString(1),
r.getBigDecimal(2),
r.getBigDecimal(3));
}
static Trade of(JSONArray r) {
return new Trade(
Util.decode(r.getString(0)),
r.getLong(1),
r.getString(2),
Util.of(r.getString(3), Side::valueOf),
r.getBigDecimal(4),
r.getBigDecimal(5));
}
/**
* {@inheritDoc}
*/
@Override
public List<Object[]> deSerialize(Object data)
throws StreamSerDeException
{
if (data == null)
{
LOG.debug("Input raw data is null.");
return nullResults;
}
String sData = data.toString();
//空字符串当作null处理,这样才可以保证is null判断的正确性
if (Strings.isNullOrEmpty(sData))
{
LOG.debug("Input raw data is null.");
return nullResults;
}
String[] attributeNameArray = this.getSchema().getAllAttributeNames();
List<Object[]> splitResults = Lists.newArrayList();
Object object = JSONObject.parse(sData);
if(object instanceof JSONObject){
dealJSONObject(splitResults,(JSONObject)object,attributeNameArray);
}
else if(object instanceof JSONArray){
JSONArray jsonArray = (JSONArray)object;
int length = jsonArray.size();
for(int i = 0;i<length;i++) {
String jsonObjectStr = jsonArray.getString(i);
JSONObject jsonObject = JSON.parseObject(jsonObjectStr);
dealJSONObject(splitResults,jsonObject,attributeNameArray);
}
}
return createAllInstance(splitResults);
}
/**
* {
* "symbol":"ETHBTC",
* "status":"TRADING",
* "baseAsset":"ETH",
* "baseAssetPrecision":8,
* "quoteAsset":"BTC",
* "quotePrecision":8,
* "orderTypes":Array[5],
* "icebergAllowed":true,
* "filters":[
* {
* "filterType":"PRICE_FILTER",
* "minPrice":"0.00000000",
* "maxPrice":"0.00000000",
* "tickSize":"0.00000100"
* },
* {
* "filterType":"PERCENT_PRICE",
* "multiplierUp":"10",
* "multiplierDown":"0.1",
* "avgPriceMins":5
* },
* {
* "filterType":"LOT_SIZE",
* "minQty":"0.00100000",
* "maxQty":"100000.00000000",
* "stepSize":"0.00100000"
* },
* {
* "filterType":"MIN_NOTIONAL",
* "minNotional":"0.00100000",
* "applyToMarket":true,
* "avgPriceMins":5
* },
* {
* "filterType":"ICEBERG_PARTS",
* "limit":10
* },
* {
* "filterType":"MAX_NUM_ALGO_ORDERS",
* "maxNumAlgoOrders":5
* }
* ]
* }
*/
@Override
protected Precisions transformPrecisions(List<String> results, ExchangeInfo info) {
String result = results.get(0);
if (useful(result)) {
JSONObject r = JSON.parseObject(result);
JSONArray symbols = r.getJSONArray("symbols");
List<Precision> precisions = new ArrayList<>(symbols.size());
for (int i = 0; i < symbols.size(); i++) {
JSONObject t = symbols.getJSONObject(i);
if (!"TRADING".equals(t.getString("status"))) {
continue;
}
String data = symbols.getString(i);
String symbol = t.getString("baseAsset") + "_" + t.getString("quoteAsset");
Integer base = t.getInteger("baseAssetPrecision");
Integer quote = t.getInteger("quotePrecision");
JSONArray filters = t.getJSONArray("filters");
JSONObject baseFilter = null;
JSONObject priceFilter = null;
for (int j = 0; j < filters.size(); j++) {
JSONObject temp = filters.getJSONObject(j);
if ("PRICE_FILTER".equals(temp.getString("filterType"))) {
priceFilter = temp;
} else if ("LOT_SIZE".equals(temp.getString("filterType"))){
baseFilter = temp;
}
}
BigDecimal baseStep = this.getBigDecimal(baseFilter, "stepSize");
BigDecimal quoteStep = this.getBigDecimal(priceFilter, "tickSize");
BigDecimal minBase = this.getBigDecimal(baseFilter, "minQty");
BigDecimal minQuote = this.getBigDecimal(priceFilter, "minPrice");
BigDecimal maxBase = this.getBigDecimal(baseFilter, "maxQty");
BigDecimal maxQuote = this.getBigDecimal(priceFilter, "maxPrice");
Precision precision = new Precision(data, symbol, base, quote,
baseStep, quoteStep, minBase, minQuote, maxBase, maxQuote);
precisions.add(precision);
}
return new Precisions(precisions);
}
return null;
}
@Override
public void init(JSONArray param) {
defaultValStr = param.getString(0);
}
/**
* @desc get hot account or sub hot account info
* @param name account name
* @param sub true: sub hot account false:
*/
public static UserInfo getAccountInfoByName(WCS wcs, String name, boolean sub) throws Exception {
Web3j web3j = wcs.getWeb3j();
if (web3j == null) {
logger.error("getHotAccountInfo web3j is null");
return null;
}
JSONObject jsonObject = JSON.parseObject("{}");
jsonObject.put("contract", CONTRACT_NAME);
if (!sub) {
jsonObject.put("func", CONTRACT_METHOD_HOT_ACCOUNT_INFO);
} else {
jsonObject.put("func", CONTRACT_METHOD_SUB_HOT_ACCOUNT_INFO);
}
jsonObject.put("version", "");
List<Object> params = new ArrayList<>();
params.add(name);
jsonObject.put("params", params);
String data = Numeric.toHexString(jsonObject.toJSONString().getBytes());
EthCall ethCall = web3j.ethCall(Transaction.createEthCallTransaction(null, null, data, BigInteger.ZERO, false), DefaultBlockParameterName.LATEST).sendAsync().get();
String value = ethCall.getResult();
JSONArray array = JSON.parseArray(value);
if (array.size() == 0) {
logger.error("getHotAccountInfo array size 0");
return null;
}
String uid = array.getString(0);
int availAssets = array.getInteger(1);
int unAvailAssets = array.getInteger(2);
int identity = array.getInteger(3);
UserInfo userInfo = new UserInfo(uid, availAssets, unAvailAssets, identity, name);
return userInfo;
}
@Override
public void init(JSONArray param) {
tableName = param.getString(0);
fieldName = param.getString(1);
}
/**
* @desc get user info
* @param uid
*/
public static UserInfo queryUserInfo(String uid) throws Exception {
byte[] uidBytes = Arrays.copyOf(uid.getBytes(), 32);
Bytes32 uidByte32 = new Bytes32(uidBytes);
RouteManager routeManager = RouteManager.load(Config.getConfig().getRouteAddress(), routeWCS.getWeb3j(), routeWCS.getCredentials(), gasPrice, gasLimit);
List<Type> typeList = routeManager.getRoute(uidByte32).get();
if (typeList.size() != 2) {
return null;
}
Boolean existed = (Boolean)typeList.get(0).getValue();
BigInteger setId = (BigInteger)typeList.get(1).getValue();
if (!existed) {
return null;
}
Future<Utf8String> addressFuture = routeManager.m_setNames(new Uint256(setId));
String setName = addressFuture.get().toString();
JSONObject jsonObject = JSON.parseObject("{}");
jsonObject.put("contract", "Meshchain");
jsonObject.put("func", "getUserInfo");
jsonObject.put("version", "");
List<Object> params = new ArrayList<>();
params.add(uid);
jsonObject.put("params", params);
Web3j web3j = nameSetServiceMap.get(setName).getWeb3j();
if (web3j == null) {
throw new Exception("bad chain name");
}
String data = Numeric.toHexString(jsonObject.toJSONString().getBytes());
EthCall ethCall = web3j.ethCall(Transaction.createEthCallTransaction(null, null, data, BigInteger.ZERO, false), DefaultBlockParameterName.LATEST).sendAsync().get();
String value = ethCall.getResult();
JSONArray array = JSON.parseArray(value);
if (array.size() == 0) {
throw new Exception("array size = 0");
}
int availAssets = array.getInteger(0);
int unAvailAssets = array.getInteger(1);
int identity = array.getInteger(2);
String name = array.getString(3);
UserInfo userInfo = new UserInfo(uid, availAssets, unAvailAssets, identity, name);
System.out.printf("uid:%s,set id:%d\n", uid, setId.intValue());
return userInfo;
}