java - 使用 Helidon 2.0.0-M2 在 POST 方法上获取原始 JSON
问题描述
我在下面有一个 POST 端点。我想访问在处理程序方法中发送的原始 JSON。理想情况下,这可以作为字符串或转换为地图。JSON 中的数据可能会有所不同,我不想像 Pokemon 示例中那样将其转换为特定的类。
我尝试了以下两种方法,一种尝试从请求对象访问数据,另一种使用带有 String.class 的处理程序。第一个记录以下错误“SEVERE org.eclipse.yasson.internal.Unmarshaller Thread[nioEventLoopGroup-3-2,10,main]: Unexpected char 39 at (line no=1, column no=1, offset=0)” .
第二个打印 JSON “{key1:value1”的第一部分。
卷曲 POST 命令
curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:8090/datastore/type
方法一
.post("/type", this::addDataTypeItem)
private void addDataTypeItem(ServerRequest request, ServerResponse response) {
// get RAW JSON as String or Map of JSON contents
// this code does not work.
// SEVERE org.eclipse.yasson.internal.Unmarshaller Thread[nioEventLoopGroup-3-2,10,main]: Unexpected char 39 at (line no=1, column no=1, offset=0)
request.content().as(JsonObject.class)
.thenAccept(jo -> printValue(jo));
}
方法二
.post("/type", Handler.create(String.class, this::addDataTypeItem))
private void addDataTypeItem(ServerRequest request, ServerResponse response, String value) {
// get RAW JSON as String or Map of JSON contents
// below prints "value: '{key1:value1,"
System.out.println("value: "+value);
}
口袋妖怪示例
.post("/pokemon", Handler.create(Pokemon.class, this::insertPokemon))
private void insertPokemon(ServerRequest request, ServerResponse response, Pokemon pokemon) {
dbClient.execute(exec -> exec
.createNamedInsert("insert-pokemon")
.indexedParam(pokemon)
.execute())
.thenAccept(count -> response.send("Inserted: " + count + " values\n"))
.exceptionally(throwable -> sendError(throwable, response));
}
在 POST 处理程序方法中将 JSON 作为字符串或 Map 获取的最佳方法是什么?
谢谢
解决方案
嗨方法2似乎工作得很好:
public static void main(final String[] args) throws IOException {
WebServer.builder(Routing.builder()
.register("/datastore", rules ->
rules.post("/type",
Handler.create(String.class, (req, res, value) -> System.out.println("String json: " + value))
)
).build()
).build()
.start()
.thenAccept(ws -> System.out.println("curl -d '{\"key1\":\"value1\", \"key2\":\"value2\"}' " +
"-H \"Content-Type: application/json\" " +
"-X POST http://localhost:" + ws.port() + "/datastore/type")
);
}
调用 curl 后:
curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:50569/datastore/type
输出:
String json: {"key1":"value1", "key2":"value2"}
推荐阅读
- bash - 如何在 linux 中运行 shell 脚本文件?
- c# - UWP Xamarin 中的 Oxyplot 未更新
- c - 如何确定头文件中 C 结构的成员?
- python - Python 列表 += 内部函数中的意外行为
- python - 我不能用 python dict 做任何事情?
- python - 如何编辑和重新腌制?
- android - Track Intent.ACTION_DELETE 是否成功卸载应用
- airflow - 使用 Cloud Proxy 的 Google Cloud Composer 和 MS SQL
- python - 如何计算python中多个字符串对中字符串的出现次数?
- javascript - 如何将自动递增的 id 添加到动态大小的可观察数组?