當前位置: 首頁>>代碼示例>>Java>>正文


Java Json類代碼示例

本文整理匯總了Java中io.vertx.core.json.Json的典型用法代碼示例。如果您正苦於以下問題:Java Json類的具體用法?Java Json怎麽用?Java Json使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Json類屬於io.vertx.core.json包,在下文中一共展示了Json類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: addItem

import io.vertx.core.json.Json; //導入依賴的package包/類
private void addItem(RoutingContext rc) {
    String body = rc.getBodyAsString();
    if (body != null) {
        Item item = Json.decodeValue(body, Item.class);

        if (item.getQuantity() == 0) {
            redis.hdel("my-shopping-list", item.getName(), res -> {
                if (res.failed()) {
                    rc.fail(res.cause());
                } else {
                    getShoppingList(rc);
                }
            });
        } else {
            redis.hset("my-shopping-list", item.getName(), Integer.toString(item.getQuantity()), res -> {
                if (res.failed()) {
                    rc.fail(res.cause());
                } else {
                    getShoppingList(rc);
                }
            });
        }
    } else {
        rc.response().setStatusCode(400).end();
    }
}
 
開發者ID:cescoffier,項目名稱:vertx-chtijug-2017,代碼行數:27,代碼來源:MyShoppingListVerticle.java

示例2: decodeBodyToObject

import io.vertx.core.json.Json; //導入依賴的package包/類
public static <T> T decodeBodyToObject(RoutingContext routingContext, Class<T> clazz) {
  try {
    return Json.decodeValue(routingContext.getBodyAsString("UTF-8"), clazz);
  } catch (DecodeException exception) {
    routingContext.fail(exception);
    return null;
  }
}
 
開發者ID:BillyYccc,項目名稱:vertx-postgresql-starter,代碼行數:9,代碼來源:RestApiUtil.java

示例3: start

import io.vertx.core.json.Json; //導入依賴的package包/類
@Override
public void start(Future<Void> startFuture) throws Exception {
    Json.mapper.registerModule(new JavaTimeModule());
	FileSystem vertxFileSystem = vertx.fileSystem();
    vertxFileSystem.readFile("swagger.json", readFile -> {
        if (readFile.succeeded()) {
            Swagger swagger = new SwaggerParser().parse(readFile.result().toString(Charset.forName("utf-8")));
            Router swaggerRouter = SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, vertx.eventBus(), new OperationIdServiceIdResolver());
        
            deployVerticles(startFuture);
            
            vertx.createHttpServer() 
                .requestHandler(swaggerRouter::accept) 
                .listen(8080);
            startFuture.complete();
        } else {
        	startFuture.fail(readFile.cause());
        }
    });        		        
}
 
開發者ID:cliffano,項目名稱:swaggy-jenkins,代碼行數:21,代碼來源:MainApiVerticle.java

示例4: getOne

import io.vertx.core.json.Json; //導入依賴的package包/類
private void getOne(RoutingContext routingContext) {
    String id = routingContext.request().getParam("id");
    try {
        Integer idAsInteger = Integer.valueOf(id);
        Article article = products.get(idAsInteger);
        if (article == null) {
            // Not found
            routingContext.response().setStatusCode(404).end();
        } else {
            routingContext.response()
                .setStatusCode(200)
                .putHeader("content-type", "application/json; charset=utf-8")
                .end(Json.encodePrettily(article));
        }
    } catch (NumberFormatException e) {
        routingContext.response().setStatusCode(400).end();
    }
}
 
開發者ID:cescoffier,項目名稱:introduction-to-vert.x,代碼行數:19,代碼來源:MyFirstVerticle.java

示例5: updateOne

import io.vertx.core.json.Json; //導入依賴的package包/類
private void updateOne(RoutingContext routingContext) {
    String id = routingContext.request().getParam("id");
    try {
        Integer idAsInteger = Integer.valueOf(id);
        Article article = products.get(idAsInteger);
        if (article == null) {
            // Not found
            routingContext.response().setStatusCode(404).end();
        } else {
            JsonObject body = routingContext.getBodyAsJson();
            article.setTitle(body.getString("title")).setUrl(body.getString("url"));
            products.put(idAsInteger, article);
            routingContext.response()
                .setStatusCode(200)
                .putHeader("content-type", "application/json; charset=utf-8")
                .end(Json.encodePrettily(article));
        }
    } catch (NumberFormatException e) {
        routingContext.response().setStatusCode(400).end();
    }

}
 
開發者ID:cescoffier,項目名稱:introduction-to-vert.x,代碼行數:23,代碼來源:MyFirstVerticle.java

示例6: writeJsonResponse

import io.vertx.core.json.Json; //導入依賴的package包/類
/**
 * Returns a handler writing the received {@link AsyncResult} to the routing context and setting the HTTP status to
 * the given status.
 * @param context the routing context
 * @param status the status
 * @return the handler
 */
private static <T> Handler<AsyncResult<T>> writeJsonResponse(RoutingContext context, int status) {
    return ar -> {
        if (ar.failed()) {
            if (ar.cause() instanceof NoSuchElementException) {
                context.response().setStatusCode(404).end(ar.cause().getMessage());
            } else {
                context.fail(ar.cause());
            }
        } else {
            context.response().setStatusCode(status)
                .putHeader("content-type", "application/json; charset=utf-8")
                .end(Json.encodePrettily(ar.result()));
        }
    };
}
 
開發者ID:cescoffier,項目名稱:introduction-to-vert.x,代碼行數:23,代碼來源:ActionHelper.java

示例7: checkThatWeCanAdd

import io.vertx.core.json.Json; //導入依賴的package包/類
@Test
public void checkThatWeCanAdd(TestContext context) {
    Async async = context.async();
    final String json = Json.encodePrettily(new Article("Some title", "Some url"));
    vertx.createHttpClient().post(port, "localhost", "/api/articles")
        .putHeader("Content-Type", "application/json")
        .putHeader("Content-Length", Integer.toString(json.length()))
        .handler(response -> {
            context.assertEquals(response.statusCode(), 201);
            context.assertTrue(response.headers().get("content-type").contains("application/json"));
            response.bodyHandler(body -> {
                Article article = Json.decodeValue(body.toString(), Article.class);
                context.assertEquals(article.getTitle(), "Some title");
                context.assertEquals(article.getUrl(), "Some url");
                context.assertNotNull(article.getId());
                async.complete();
            });
        })
        .write(json)
        .end();
}
 
開發者ID:cescoffier,項目名稱:introduction-to-vert.x,代碼行數:22,代碼來源:MyFirstVerticleTest.java

示例8: decodeFromWire

import io.vertx.core.json.Json; //導入依賴的package包/類
@Override
public String[] decodeFromWire(int position, Buffer buffer) {
    int pos = position;

    int length = buffer.getInt(pos);

    // Get JSON string by it`s length
    // Jump 4 because getInt() == 4 bytes
    String jsonStr = buffer.getString(pos+=4, pos+length);

    return Json.decodeValue(jsonStr, String[].class);
}
 
開發者ID:bpark,項目名稱:chlorophytum-semantics,代碼行數:13,代碼來源:StringArrayCodec.java

示例9: decodeFromWire

import io.vertx.core.json.Json; //導入依賴的package包/類
@Override
public PersonName decodeFromWire(int position, Buffer buffer) {
    int pos = position;

    int length = buffer.getInt(pos);

    // Get JSON string by it`s length
    // Jump 4 because getInt() == 4 bytes
    String jsonStr = buffer.getString(pos+=4, pos+length);

    return Json.decodeValue(jsonStr, PersonName.class);
}
 
開發者ID:bpark,項目名稱:chlorophytum-semantics,代碼行數:13,代碼來源:PersonNameCodec.java

示例10: handle

import io.vertx.core.json.Json; //導入依賴的package包/類
@Override
public void handle(RoutingContext routingContext) {
    String content = routingContext.getBodyAsString();
    final ChatMessage chatMessage = Json.decodeValue(content, ChatMessage.class);

    String messageId = UUID.randomUUID().toString();
    chatMessage.setId(messageId);
    chatMessage.setCreated(System.currentTimeMillis());

    redisClient.hset(MESSAGES, messageId, Json.encode(chatMessage), result -> {});

    vertx.eventBus().send(ChatAddresses.MESSAGES.getAddress(), chatMessage);

    routingContext.response()
            .setStatusCode(201)
            .putHeader("content-type", "application/json; charset=utf-8")
            .end(messageId);
}
 
開發者ID:bpark,項目名稱:chlorophytum-semantics,代碼行數:19,代碼來源:CreateMessageHandler.java

示例11: decodeFromWire

import io.vertx.core.json.Json; //導入依賴的package包/類
@Override
public ChatMessage decodeFromWire(int position, Buffer buffer) {
    int pos = position;

    int length = buffer.getInt(pos);

    // Get JSON string by it`s length
    // Jump 4 because getInt() == 4 bytes
    String jsonStr = buffer.getString(pos+=4, pos+length);

    return Json.decodeValue(jsonStr, ChatMessage.class);
}
 
開發者ID:bpark,項目名稱:chlorophytum-semantics,代碼行數:13,代碼來源:ChatMessageCodec.java

示例12: buildSuccess

import io.vertx.core.json.Json; //導入依賴的package包/類
public <B> void buildSuccess(RoutingContext routingContext, B body) {
    LOG.debug("Building success message");

    Completable.fromAction(
            () ->
                    routingContext.response()
                            .setStatusCode(200)
                            .putHeader(CONTENT_TYPE_KEY, CONTENT_TYPE_VALUE)
                            .putHeader("Link", buildLinkHeaderValue())
                            .end(body != null ? Json.encodePrettily(body) : StringUtils.EMPTY))
            .subscribeOn(Schedulers.io())
            .subscribe(
                    () -> {}, // Do nothing on success
                    (ex) -> routingContext.fail(ex)
            );
}
 
開發者ID:Atypon-OpenSource,項目名稱:wayf-cloud,代碼行數:17,代碼來源:ResponseWriter.java

示例13: write

import io.vertx.core.json.Json; //導入依賴的package包/類
private static void write(HttpServerResponse response, Problem problem) {
    int statusCode = problem.getStatus() != null ? problem.getStatus().getStatusCode() : Status.OK.getStatusCode();

    response.setChunked(true).putHeader("Content-Type", "application/problem+json");

    try {
        response
            .setStatusCode(statusCode)
            .write(Json.encode(problem));
    } catch (EncodeException e) {
        LOG.error("Error while writing problem to JSON", e);
        response
            .setStatusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
            .write(INTERNAL_SERVER_ERROR);
    } finally {
        response.end();
    }
}
 
開發者ID:valuelogic,項目名稱:vertx-web-problem,代碼行數:19,代碼來源:ProblemHandlerImpl.java

示例14: handle

import io.vertx.core.json.Json; //導入依賴的package包/類
@Override
public Promise<StateTrigger<Msg<Json>>> handle(Msg<JsonArray> msg) throws Throwable {
    List list = msg.body().stream()
        .map(
            obj -> authorizer
                .authorize(
                    Authorizer.AuthorizeParams.builder()
                        .action(action)
                        .userId(msg.userId())
                        .request(obj)
                        .build()
                )
        )
        .collect(Collectors.toList());

    return authorize(list, msg);
}
 
開發者ID:codefacts,項目名稱:Elastic-Components,代碼行數:18,代碼來源:AuthorizeAllStateHandlerImpl.java

示例15: registerMultiConfigEntryProvider

import io.vertx.core.json.Json; //導入依賴的package包/類
/**
 * Registers a handler for accessing multiple configuration keys (input: String[] (Json),
 * reply type: Map<String,String></String,String> (Json).
 * @param address the event bus address to register.
 * @param eventBus the event bus.
 * @return the consumer registered.
 */
public static MessageConsumer<String> registerMultiConfigEntryProvider(String address, EventBus eventBus){
    MessageConsumer<String> consumer = eventBus.consumer(address);
    consumer.handler(h -> {
        String val = h.body();
        Configuration config = ConfigurationProvider.getConfiguration();
        Map<String,String> entries = new TreeMap<>();
        if(val!=null){
            String[] sections = Json.decodeValue(val, String[].class);
            for (String section : sections) {
                if(section!=null) {
                    entries.putAll(config.with(ConfigurationFunctions.section(section)).getProperties());
                }
            }
        }else{
            entries.putAll(config.getProperties());
        }
        h.reply(Json.encode(entries));
    });
    return consumer;
}
 
開發者ID:apache,項目名稱:incubator-tamaya-sandbox,代碼行數:28,代碼來源:TamayaConfigurationProducer.java


注:本文中的io.vertx.core.json.Json類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。