java - 在 Java 中将序列化的 JSON 对象转换回
问题描述
我正在编写一个 Java 应用程序,它通过 REST API 向在本地网络中运行的命名实体识别服务 ( deeppavlov ) 发出请求。
所以我通过以下方式请求数据:
String text = "Welcome to Moscow, John";
List<String> textList = new ArrayList<String>();
textList.add(text);
JSONObject json = new JSONObject();
json.put("x", textList);
String URL = "http://localhost:5005/model";
HttpClient client = HttpClient.newBuilder()
.version(Version.HTTP_1_1)
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(URL))
.header("accept", "application/json")
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofString(json.toString()))
.build();
try {
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
System.out.println(response.body());
System.out.println(response.body().getClass());
} catch (IOException | InterruptedException e) {
}
结果我得到:
[[["欢迎","to","莫斯科",",","约翰"],["O","O","B-GPE","O","B-PERSON"]] ] 类 java.lang.String
它是一个字符串,我不知道如何将其转换为对象、数组、映射或列表以进行迭代。请帮忙。
解决方案
它取决于您用来反序列化字符串的库。看来您正在使用 org json 代码,因此可能的解决方案使用JSONTokener
:
将 JSON (RFC 4627) 编码的字符串解析为相应的对象
然后使用方法nextValue
:
从输入中返回下一个值。可以是 JSONObject、JSONArray、String、Boolean、Integer、Long、Double 或 JSONObject#NULL。
代码如下
Object jsonObject = new JSONTokener(jsonAsString).nextValue();
推荐阅读
- express - 针对快速服务器的 Axios 发布请求成功使用图像,使用 .mp4 文件失败
- go - PromQL 查询以绘制传入请求的速率
- css - Flex 盒子水平对齐
- c# - 这是使用 ConfigureAwait(false) 的正确方法吗?
- amazon-web-services - IAM 权限策略是否可以用于允许访问跨账户资源?
- java - 在测验应用程序中显示结果 + 不正确/正确的对话框
- python - 使用带有--no-console的pyinstaller时如何将错误信息记录到文件中?
- unit-testing - Netbeans 11.2 未找到测试
- rabbitmq - 我可以将 rabbitmq 中的所有消息发布到 REST API 吗?
- javascript - 使用 MSAL.js 循环访问租户