当前位置: 首页>>代码示例>>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;未经允许,请勿转载。