io.vertx.core.json.JsonArray类的使用及代码示例

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

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

JsonArray介绍

[英]A representation of a JSON array in Java.

Unlike some other languages Java does not have a native understanding of JSON. To enable JSON to be used easily in Vert.x code we use this class to encapsulate the notion of a JSON array. The implementation adheres to the RFC-7493 to support Temporal data types as well as binary data.

Please see the documentation for more information.
[中]Java中JSON数组的表示形式。
与其他一些语言不同,Java对JSON没有本机理解。使JSON在Vert中易于使用。我们使用这个类来封装JSON数组的概念。该实现遵循RFC-7493以支持时态数据类型和二进制数据。
有关更多信息,请参阅文档。

代码示例

代码示例来源:origin: vert-x3/vertx-examples

@Override
public void getTransactionsList(
 List<String> from,
 List<String> to,
 List<String> message,
 OperationRequest context, Handler<AsyncResult<OperationResponse>> resultHandler){
 List<Transaction> results = persistence.getFilteredTransactions(this.constructFilterPredicate(from, to, message));
 resultHandler.handle(Future.succeededFuture(
  OperationResponse.completedWithJson(
   new JsonArray(results.stream().map(Transaction::toJson).collect(Collectors.toList()))
  )
 ));
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testEncodeToBuffer() throws Exception {
 jsonArray.add("foo");
 jsonArray.add(123);
 jsonArray.add(1234l);
 jsonArray.add(1.23f);
 jsonArray.add(2.34d);
 jsonArray.add(true);
 byte[] bytes = TestUtils.randomByteArray(10);
 jsonArray.add(bytes);
 jsonArray.addNull();
 jsonArray.add(new JsonObject().put("foo", "bar"));
 jsonArray.add(new JsonArray().add("foo").add(123));
 String strBytes = Base64.getEncoder().encodeToString(bytes);
 Buffer expected = Buffer.buffer("[\"foo\",123,1234,1.23,2.34,true,\"" + strBytes + "\",null,{\"foo\":\"bar\"},[\"foo\",123]]", "UTF-8");
 Buffer json = jsonArray.toBuffer();
 assertArrayEquals(expected.getBytes(), json.getBytes());
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testToJsonArray() {
 List<Object> list = new ArrayList<>();
 list.add("the_string");
 list.add(4);
 list.add(true);
 list.add(new AsciiString("the_charsequence"));
 list.add(new BigInteger("1234567"));
 list.add(Buffer.buffer("hello"));
 list.add(Collections.singletonMap("nested", 4));
 list.add(Arrays.asList(1, 2, 3));
 JsonArray json = (JsonArray) ConversionHelper.toObject(list);
 assertEquals(8, json.size());
 assertEquals("the_string", json.getString(0));
 assertEquals(4, (int)json.getInteger(1));
 assertEquals(true, json.getBoolean(2));
 assertEquals("the_charsequence", json.getString(3));
 assertEquals(1234567, (int)json.getInteger(4));
 assertEquals("hello", new String(json.getBinary(5)));
 assertEquals(new JsonObject().put("nested", 4), json.getJsonObject(6));
 assertEquals(new JsonArray().add(1).add(2).add(3), json.getJsonArray(7));
}

代码示例来源:origin: eclipse-vertx/vert.x

static void toJson(PemTrustOptions obj, java.util.Map<String, Object> json) {
  if (obj.getCertPaths() != null) {
   JsonArray array = new JsonArray();
   obj.getCertPaths().forEach(item -> array.add(item));
   json.put("certPaths", array);
  }
  if (obj.getCertValues() != null) {
   JsonArray array = new JsonArray();
   obj.getCertValues().forEach(item -> array.add(java.util.Base64.getEncoder().encodeToString(item.getBytes())));
   json.put("certValues", array);
  }
 }
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testCreateFromBuffer() {
 JsonArray excepted = new JsonArray();
 excepted.add("foobar");
 excepted.add(123);
 Buffer buf = Buffer.buffer(excepted.encode());
 assertEquals(excepted, new JsonArray(buf));
}

代码示例来源:origin: vert-x3/vertx-examples

private void handleAddProduct(RoutingContext routingContext) {
 HttpServerResponse response = routingContext.response();
 SQLConnection conn = routingContext.get("conn");
 JsonObject product = routingContext.getBodyAsJson();
 conn.updateWithParams("INSERT INTO products (name, price, weight) VALUES (?, ?, ?)",
  new JsonArray().add(product.getString("name")).add(product.getFloat("price")).add(product.getInteger("weight")), query -> {
   if (query.failed()) {
    sendError(500, response);
   } else {
    response.end();
   }
  });
}

代码示例来源:origin: xenv/gushici

private void getHelpFromRedis(Message message) {
  redisClient.lrange(Key.REDIS_HELP_LIST, 0, -1, res -> {
    if (res.succeeded()) {
      JsonArray array = res.result();
      JsonArray newArray = array.stream()
        .map(text -> {
          String prefix = config().getString("api.url", "http://localhost/");
          return new JsonObject((String) text).stream()
            .collect(Collectors.toMap(Map.Entry::getKey,
              v -> prefix + v.getValue().toString().replace(":", "/")));
        })
        .collect(JsonCollector.toJsonArray());
      message.reply(newArray);
    } else {
      log.error("Fail to get data from Redis", res.cause());
      message.fail(500, res.cause().getMessage());
    }
  });
}

代码示例来源:origin: sczyh30/vertx-kue

@Override
public JobService getIdsByState(JobState state, Handler<AsyncResult<List<Long>>> handler) {
 client.zrange(RedisHelper.getStateKey(state), 0, -1, r -> {
  if (r.succeeded()) {
   List<Long> list = r.result().stream()
    .map(e -> RedisHelper.numStripFIFO((String) e))
    .collect(Collectors.toList());
   handler.handle(Future.succeededFuture(list));
  } else {
   handler.handle(Future.failedFuture(r.cause()));
  }
 });
 return this;
}

代码示例来源:origin: io.knotx/knotx-core

public Fragment(JsonObject fragment) {
 JsonArray knotsArray = fragment.getJsonArray(KNOTS_KEY);
 this.knots = knotsArray.stream()
   .map(entry -> new KnotTask((JsonObject) entry))
   .collect(Collectors.toList());
 this.content = fragment.getString(CONTENT_KEY);
 this.context = fragment.getJsonObject(CONTEXT_KEY, new JsonObject());
 this.fallback = fragment.getString(FALLBACK_KEY);
 this.attributes = fragment.getJsonObject(ATTRUBUTES_KEY, new JsonObject());
}

代码示例来源:origin: sczyh30/vertx-blueprint-microservice

public Order(JsonObject json) {
 OrderConverter.fromJson(json, this);
 if (json.getValue("products") instanceof String) {
  this.products = new JsonArray(json.getString("products"))
   .stream()
   .map(e -> (JsonObject) e)
   .map(ProductTuple::new)
   .collect(Collectors.toList());
 }
}

代码示例来源:origin: vert-x3/vertx-web

private void fetchMessages(List<String> messages) {
  client.post("/test/400/8ne8e94a/xhr", onSuccess(resp -> {
   assertEquals(200, resp.statusCode());
   resp.bodyHandler(buffer -> {
    String body = buffer.toString();
    if (body.startsWith("a")) {
     JsonArray content = new JsonArray(body.substring(1));
     messages.addAll(content.stream().map(Object::toString).collect(toList()));
    }
    if (messages.size() < 2) {
     fetchMessages(messages);
    } else {
     assertEquals(Arrays.asList("Hello", "World"), messages);
     testComplete();
    }
   });
  })).end();
 }
}

代码示例来源:origin: silentbalanceyh/vertx-zero

public <T> Future<Boolean> deleteAsync(final JsonObject filters, final String pojo) {
  return findAsync(filters)
      .compose(Ux.fnJArray(this.analyzer.getPojoFile()))
      .compose(array -> Future.succeededFuture(array.stream()
          .map(item -> (JsonObject) item)
          .map(item -> item.getValue("key"))
          .collect(Collectors.toList())))
      .compose(item -> Future.succeededFuture(item.toArray()))
      .compose(ids -> this.deleteByIdAsync(ids));
}

代码示例来源:origin: io.vertx/vertx-codegen

private static <T> List<T> fromArray(JsonObject obj, String name, Function<Object, T> converter) {
 JsonArray array = obj.getJsonArray(name);
 if (array != null) {
  return array.stream().map(converter).collect(Collectors.toList());
 } else {
  return null;
 }
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testStream() {
 jsonArray.add("foo");
 jsonArray.add(123);
 JsonObject obj = new JsonObject().put("foo", "bar");
 jsonArray.add(obj);
 List<Object> list = jsonArray.stream().collect(Collectors.toList());
 Iterator<Object> iter = list.iterator();
 assertTrue(iter.hasNext());
 Object entry = iter.next();
 assertEquals("foo", entry);
 assertTrue(iter.hasNext());
 entry = iter.next();
 assertEquals(123, entry);
 assertTrue(iter.hasNext());
 entry = iter.next();
 assertEquals(obj, entry);
 assertFalse(iter.hasNext());
}

代码示例来源:origin: eclipse-vertx/vert.x

private void testStreamCorrectTypes(JsonObject object) {
 object.getJsonArray("object1").stream().forEach(innerMap -> {
  assertTrue("Expecting JsonObject, found: " + innerMap.getClass().getCanonicalName(), innerMap instanceof JsonObject);
 });
}

代码示例来源:origin: xenv/gushici

@Override
public void start(Future<Void> startFuture) {
  vertx.eventBus().consumer(Key.GET_GUSHICI_FROM_REDIS, this::getGushiciFromRedis);
  vertx.eventBus().consumer(Key.GET_HELP_FROM_REDIS, this::getHelpFromRedis);
  redisClient = RedisClient.create(vertx, redisOptions);
  // 从 redis 缓存所有 key
  Future<JsonArray> imgKeys = Future.future(f -> redisClient.keys(Key.IMG, f));
  Future<JsonArray> jsonKeys = Future.future(f -> redisClient.keys(Key.JSON, f));
  CompositeFuture.all(Arrays.asList(imgKeys, jsonKeys)).setHandler(v -> {
    if (v.succeeded()) {
      imgKeys.result().addAll(jsonKeys.result())
        .stream()
        .forEach(key -> keysInRedis.insert((String) key));
      startFuture.complete();
    } else {
      log.error("DataService fail to start", v.cause());
      startFuture.fail(v.cause());
    }
  });
}

代码示例来源:origin: jponge/vertx-in-action

private void listCommand(NetSocket socket) {
 vertx.eventBus().send("jukebox.list", "", reply -> {
  if (reply.succeeded()) {
   JsonObject data = (JsonObject) reply.result().body();
   data.getJsonArray("files")
    .stream().forEach(name -> socket.write(name + "\n"));
  } else {
   logger.error("/list error", reply.cause());
  }
 });
}

代码示例来源:origin: io.vertx/vertx-codegen

@Override
public void methodWithHandlerAsyncResultSetComplexJsonArray(Handler<AsyncResult<Set<JsonArray>>> listHandler) {
 Set<JsonArray> set = new LinkedHashSet<>(Arrays.asList(new JsonArray().add(new JsonObject().put("foo", "hello")), new JsonArray().add(new JsonObject().put("bar", "bye"))));
 listHandler.handle(Future.succeededFuture(set));
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testDecode() throws Exception {
 byte[] bytes = TestUtils.randomByteArray(10);
 String strBytes = Base64.getEncoder().encodeToString(bytes);
 Instant now = Instant.now();
 String strInstant = ISO_INSTANT.format(now);
 String json = "{\"mystr\":\"foo\",\"myint\":123,\"mylong\":1234,\"myfloat\":1.23,\"mydouble\":2.34,\"" +
  "myboolean\":true,\"mybinary\":\"" + strBytes + "\",\"myinstant\":\"" + strInstant + "\",\"mynull\":null,\"myobj\":{\"foo\":\"bar\"},\"myarr\":[\"foo\",123]}";
 JsonObject obj = new JsonObject(json);
 assertEquals(json, obj.encode());
 assertEquals("foo", obj.getString("mystr"));
 assertEquals(Integer.valueOf(123), obj.getInteger("myint"));
 assertEquals(Long.valueOf(1234), obj.getLong("mylong"));
 assertEquals(Float.valueOf(1.23f), obj.getFloat("myfloat"));
 assertEquals(Double.valueOf(2.34d), obj.getDouble("mydouble"));
 assertTrue(obj.getBoolean("myboolean"));
 assertArrayEquals(bytes, obj.getBinary("mybinary"));
 assertEquals(Base64.getEncoder().encodeToString(bytes), obj.getValue("mybinary"));
 assertEquals(now, obj.getInstant("myinstant"));
 assertEquals(now.toString(), obj.getValue("myinstant"));
 assertTrue(obj.containsKey("mynull"));
 JsonObject nestedObj = obj.getJsonObject("myobj");
 assertEquals("bar", nestedObj.getString("foo"));
 JsonArray nestedArr = obj.getJsonArray("myarr");
 assertEquals("foo", nestedArr.getString(0));
 assertEquals(Integer.valueOf(123), Integer.valueOf(nestedArr.getInteger(1)));
}

代码示例来源:origin: vert-x3/vertx-examples

@Override
public void start() throws Exception {
 final JDBCClient client = JDBCClient.createShared(vertx, new JsonObject()
   .put("url", "jdbc:hsqldb:mem:test?shutdown=true")
   .put("driver_class", "org.hsqldb.jdbcDriver")
   .put("max_pool_size", 30)
   .put("user", "SA")
  if (conn.failed()) {
   System.err.println(conn.cause().getMessage());
   return;
  final SQLConnection connection = conn.result();
  connection.execute("create table test(id int primary key, name varchar(255))", res -> {
   if (res.failed()) {
     for (JsonArray line : rs.result().getResults()) {
      System.out.println(line.encode());

相关文章