com.eclipsesource.json.JsonArray类的使用及代码示例

x33g5p2x  于2022-01-21 转载在 其他  
字(12.9k)|赞(0)|评价(0)|浏览(160)

本文整理了Java中com.eclipsesource.json.JsonArray类的一些代码示例,展示了JsonArray类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。JsonArray类的具体详情如下:
包路径:com.eclipsesource.json.JsonArray
类名称:JsonArray

JsonArray介绍

[英]Represents a JSON array, i.e. an ordered collection of JSON values.

Elements can be added using the add(...) methods which accept instances of JsonValue, strings, primitive numbers, and boolean values. To replace an element of an array, use the set(int, ...) methods.

Elements can be accessed by their index using #get(int). This class also supports iterating over the elements in document order using an #iterator() or an enhanced for loop:

for( JsonValue value : jsonArray ) { 
... 
}

An equivalent List can be obtained from the method #values().

Note that this class is not thread-safe. If multiple threads access a JsonArray instance concurrently, while at least one of these threads modifies the contents of this array, access to the instance must be synchronized externally. Failure to do so may lead to an inconsistent state.

This class is not supposed to be extended by clients.
[中]表示JSON数组,即JSON值的有序集合。
可以使用add(...)方法添加元素,这些方法接受JsonValue、字符串、基元数和布尔值的实例。要替换数组的元素,请使用set(int, ...)方法。
可以使用#get(int)通过其索引访问元素。此类还支持使用#迭代器()或增强的for循环按文档顺序迭代元素:

for( JsonValue value : jsonArray ) { 
... 
}

可以通过方法#values()获得等效列表。
请注意,此类不是线程安全的。如果多个线程同时访问JsonArray实例,而其中至少一个线程修改此数组的内容,则必须从外部同步对该实例的访问。不这样做可能会导致状态不一致。
这个类不应该被客户端扩展。

代码示例

代码示例来源:origin: ralfstx/minimal-json

private static JsonValue extractTimes(JsonArray measurements) {
 JsonArray result = new JsonArray();
 for (JsonValue measurement : measurements) {
  result.add(measurement.asObject().get("processed"));
 }
 return result;
}

代码示例来源:origin: ralfstx/minimal-json

@Override
void write(JsonWriter writer) throws IOException {
 writer.writeArrayOpen();
 Iterator<JsonValue> iterator = iterator();
 if (iterator.hasNext()) {
  iterator.next().write(writer);
  while (iterator.hasNext()) {
   writer.writeArraySeparator();
   iterator.next().write(writer);
  }
 }
 writer.writeArrayClose();
}

代码示例来源:origin: ralfstx/minimal-json

/**
 * Creates a new JsonArray that contains the JSON representations of the given strings.
 *
 * @param strings
 *          the strings to be included in the new JSON array
 * @return a new JSON array that contains the given strings
 */
public static JsonArray array(String... strings) {
 if (strings == null) {
  throw new NullPointerException("values is null");
 }
 JsonArray array = new JsonArray();
 for (String value : strings) {
  array.add(value);
 }
 return array;
}

代码示例来源:origin: BTCPrivate/bitcoin-private-full-node-wallet

public synchronized String getSuccessfulOperationTXID(String opID)
    throws WalletCallException, IOException, InterruptedException {
  String TXID = null;
  JsonArray response = this.executeCommandAndGetJsonArray(
      "z_getoperationstatus", wrapStringParameter("[\"" + opID + "\"]"));
  JsonObject jsonStatus = response.get(0).asObject();
  JsonValue opResultValue = jsonStatus.get("result");
  if (opResultValue != null) {
    JsonObject opResult = opResultValue.asObject();
    if (opResult.get("txid") != null) {
      TXID = opResult.get("txid").asString();
    }
  }
  return TXID;
}

代码示例来源:origin: BTCPrivate/bitcoin-private-full-node-wallet

JsonObject toArgument = new JsonObject();
toArgument.set("address", to);
if (hexMemo.length() >= 2) {
  toArgument.set("memo", hexMemo.toString());
toArgument.set("amount", "\uFFFF\uFFFF\uFFFF\uFFFF\uFFFF");
JsonArray toMany = new JsonArray();
toMany.add(toArgument);
String toManyBeforeReplace = toMany.toString();
int firstIndex = toManyBeforeReplace.indexOf(amountPattern);
int lastIndex = toManyBeforeReplace.lastIndexOf(amountPattern);
String toManyArrayStr = toMany.toString().replace(
    amountPattern,
    "\"amount\":" + new DecimalFormat("########0.00######", decSymbols).format(Double.valueOf(amount)));
JsonArray toManyVerificationArr = Json.parse(toManyArrayStr).asArray();
BigDecimal bdFinalAmount =
    new BigDecimal(toManyVerificationArr.get(0).asObject().getDouble("amount", -1));
BigDecimal difference = bdAmout.subtract(bdFinalAmount).abs();
if (difference.compareTo(new BigDecimal("0.000000015")) >= 0) {

代码示例来源:origin: samczsun/Skype4J

public void load() throws ConnectionException {
  String uuid = id.substring(3); // trims the string "28:"
  JsonObject root = Endpoints.AGENT_INFO.open(skype, uuid)
      .expect(200, "While fetching agent info")
      .as(JsonObject.class)
      .get();
  JsonArray descriptions = root.get("agentDescriptions").asArray();
  if (descriptions.size() > 1) {
    throw Skype.UNEXPECTED;
  }
  JsonObject object = descriptions.get(0).asObject();
  this.displayName = Utils.getString(object, "displayName");
  this.description = Utils.getString(object, "description");
  this.developer = Utils.getString(object, "developer");
  this.extra = Utils.getString(object, "extra");
  this.userTileSmallUrl = Utils.getString(object, "userTileSmallUrl");
  this.userTileMediumUrl = Utils.getString(object, "userTileMediumUrl");
  this.userTileLargeUrl = Utils.getString(object, "userTileLargeUrl");
  this.userTileExtraLargeUrl = Utils.getString(object, "userTileExtraLargeUrl");
  this.userTileStaticUrl = Utils.getString(object, "userTileStaticUrl");
  this.webpage = Utils.getString(object, "webpage");
  this.tos = Utils.getString(object, "tos");
  this.privacyStatement = Utils.getString(object, "privacyStatement");
  this.isTrusted = object.get("isTrusted").asBoolean();
  object.get("capabilities").asArray().iterator().forEachRemaining(value -> this.capabilities.add(value.asString()));
  object.get("supportedLocales").asArray().iterator().forEachRemaining(value -> this.supportedLocales.add(value.asString()));
  this.agentType = Utils.getString(object, "agentType");
  this.starRating = object.get("starRating").asDouble();
}

代码示例来源:origin: com.github.wnameless/json-flattener

private JsonValue findOrCreateJsonObject(JsonValue currentVal, String objKey,
  Integer aryIdx) {
 if (objKey != null) {
  JsonObject jsonObj = currentVal.asObject();
  if (jsonObj.get(objKey) == null) {
   JsonValue obj = Json.object();
   jsonObj.add(objKey, obj);
   return obj;
  }
  return jsonObj.get(objKey);
 } else { // aryIdx != null
  JsonArray jsonAry = currentVal.asArray();
  if (jsonAry.size() <= aryIdx || jsonAry.get(aryIdx).equals(Json.NULL)) {
   JsonValue obj = Json.object();
   assureJsonArraySize(jsonAry, aryIdx);
   jsonAry.set(aryIdx, obj);
   return obj;
  }
  return jsonAry.get(aryIdx);
 }
}

代码示例来源:origin: BTCPrivate/bitcoin-private-full-node-wallet

private void decomposeJSONValue(String name, JsonValue val, Map<String, String> map) {
  if (val.isObject()) {
    JsonObject obj = val.asObject();
    for (String memberName : obj.names()) {
      this.decomposeJSONValue(name + "." + memberName, obj.get(memberName), map);
    }
  } else if (val.isArray()) {
    JsonArray arr = val.asArray();
    for (int i = 0; i < arr.size(); i++) {
      this.decomposeJSONValue(name + "[" + i + "]", arr.get(i), map);
    }
  } else {
    map.put(name, val.toString());
  }
}

代码示例来源:origin: box/box-java-sdk

RealtimeServerConnection(BoxAPIConnection api) {
  BoxAPIRequest request = new BoxAPIRequest(api, EVENT_URL.build(api.getBaseURL()), "OPTIONS");
  BoxJSONResponse response = (BoxJSONResponse) request.send();
  JsonObject jsonObject = JsonObject.readFrom(response.getJSON());
  JsonArray entries = jsonObject.get("entries").asArray();
  JsonObject firstEntry = entries.get(0).asObject();
  this.serverURLString = firstEntry.get("url").asString();
  this.retries = Integer.parseInt(firstEntry.get("max_retries").asString());
  this.timeout = firstEntry.get("retry_timeout").asInt();
  this.api = api;
}

代码示例来源:origin: box/box-java-sdk

JsonObject responseJSON = JsonObject.readFrom(batchResponse.getJSON());
List<BoxAPIResponse> responses = new ArrayList<BoxAPIResponse>();
Iterator<JsonValue> responseIterator = responseJSON.get("responses").asArray().iterator();
while (responseIterator.hasNext()) {
  JsonObject jsonResponse = responseIterator.next().asObject();
  BoxAPIResponse response = null;
  if (jsonResponse.get("headers") != null) {
    JsonObject batchResponseHeadersObject = jsonResponse.get("headers").asObject();
    for (JsonObject.Member member : batchResponseHeadersObject) {
      String headerName = member.getName();

代码示例来源:origin: samczsun/Skype4J

private static JsonObject getObject(SkypeImpl skype, String username) throws ConnectionException {
  JsonArray array = Endpoints.PROFILE_INFO
      .open(skype)
      .expect(200, "While getting contact info")
      .as(JsonArray.class)
      .post(new JsonObject()
          .add("usernames", new JsonArray()
              .add(username)
          )
      );
  return array.get(0).asObject();
}

代码示例来源:origin: org.wildfly.swarm/fraction-list

private void addDependencies(JsonObject fraction, FractionDescriptor parent) {
  fraction.get("fractionDependencies").asArray().forEach(entry -> {
    JsonObject dependency = entry.asObject();
    FractionDescriptor descriptor = getFractionDescriptor(dependency);
    if (parent != null) {
      parent.addDependency(descriptor);
    }
    addDependencies(dependency, descriptor);
  });
}

代码示例来源:origin: samczsun/Skype4J

private void updateContactInfo() throws ConnectionException {
  if (this.skype instanceof FullClient) {
    JsonObject obj = Endpoints.GET_CONTACT_BY_ID
        .open(skype, skype.getUsername(), username)
        .as(JsonObject.class)
        .expect(200, "While getting contact info")
        .get();
    if (obj.get("contacts").asArray().size() > 0) {
      JsonObject contact = obj.get("contacts").asArray().get(0).asObject();
      update(contact);
    } else {
      this.isAuthorized = false;
      this.isBlocked = false;
    }
  }
}

代码示例来源:origin: BTCPrivate/bitcoin-private-full-node-wallet

public synchronized String[] getWalletPublicAddressesWithUnspentOutputs()
    throws WalletCallException, IOException, InterruptedException {
  JsonArray jsonUnspentOutputs = executeCommandAndGetJsonArray("listunspent", "0");
  Set<String> addresses = new HashSet<>();
  for (int i = 0; i < jsonUnspentOutputs.size(); i++) {
    JsonObject outp = jsonUnspentOutputs.get(i).asObject();
    addresses.add(outp.getString("address", "ERROR!"));
  }
  return addresses.toArray(new String[0]);
}

代码示例来源:origin: io.thorntail/config-api-generator

public List<GeneratorTarget> getGeneratorTargets() {
  List<GeneratorTarget> references = new ArrayList<>();
  json.get("generatorTargets").asArray().forEach(ref -> {
    //JsonObject atts = ref.asObject();
    references.add(new GeneratorTarget(ref.asString()));
  });
  return references;
}

代码示例来源:origin: box/box-java-sdk

/**
 * Add BoxMetaDataFilter to the JsonArray boxMetadataFilterRequestArray.
 * @param @param bmf accepts a filter that has templateKey, scope, and filters populated.
 * @return JsonArray that is formated Json request
 */
private JsonArray formatBoxMetadataFilterRequest() {
  JsonArray boxMetadataFilterRequestArray = new JsonArray();
  JsonObject boxMetadataFilter = new JsonObject()
      .add("templateKey", this.metadataFilter.getTemplateKey())
      .add("scope", this.metadataFilter.getScope())
      .add("filters", this.metadataFilter.getFiltersList());
  boxMetadataFilterRequestArray.add(boxMetadataFilter);
  return boxMetadataFilterRequestArray;
}

代码示例来源:origin: BTCPrivate/bitcoin-private-full-node-wallet

public synchronized boolean isCompletedOperationSuccessful(String opID)
    throws WalletCallException, IOException, InterruptedException {
  JsonArray response = this.executeCommandAndGetJsonArray(
      "z_getoperationstatus", wrapStringParameter("[\"" + opID + "\"]"));
  JsonObject jsonStatus = response.get(0).asObject();
  String status = jsonStatus.getString("status", "ERROR");
  Log.info("Operation " + opID + " status is " + response + ".");
  if (status.equalsIgnoreCase("success")) {
    return true;
  } else if (status.equalsIgnoreCase("error") || status.equalsIgnoreCase("failed")) {
    return false;
  } else {
    throw new WalletCallException("Unexpected final operation status response from wallet: " + response.toString());
  }
}

代码示例来源:origin: BTCPrivate/bitcoin-private-full-node-wallet

public synchronized String getOperationFinalErrorMessage(String opID)
    throws WalletCallException, IOException, InterruptedException {
  JsonArray response = this.executeCommandAndGetJsonArray(
      "z_getoperationstatus", wrapStringParameter("[\"" + opID + "\"]"));
  JsonObject jsonStatus = response.get(0).asObject();
  JsonObject jsonError = jsonStatus.get("error").asObject();
  return jsonError.getString("message", "ERROR!");
}

代码示例来源:origin: ZencashOfficial/zencash-swing-wallet-ui

private JsonObject getExchangeDataFromRemoteService()
  {
    JsonObject data = new JsonObject();
    
    try
    {
      URL u = new URL("https://api.coinmarketcap.com/v1/ticker/zencash");
      Reader r = new InputStreamReader(u.openStream(), "UTF-8");
      JsonArray ar = Json.parse(r).asArray();
      data = ar.get(0).asObject();
    } catch (Exception ioe)
    {
      Log.warning("Could not obtain ZEN exchange information from coinmarketcap.com due to: {0} {1}", 
            ioe.getClass().getName(), ioe.getMessage());
    }
    
    return data;
  }
}

代码示例来源:origin: box/box-android-sdk

public HashSet<String> getPropertyAsStringHashSet(String field) {
  if (mInternalCache.get(field) != null){
    return (HashSet<String>)mInternalCache.get(field);
  }
  JsonValue value = getAsJsonValue(field);
  if (value == null || value.isNull()) {
    return null;
  }
  HashSet<String> strings = new HashSet<String>(value.asArray().size());
  for (JsonValue member : value.asArray()){
    strings.add(member.asString());
  }
  mInternalCache.put(field, strings);
  return strings;
}

相关文章