首页 > 解决方案 > 在 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

它是一个字符串,我不知道如何将其转换为对象、数组、映射或列表以进行迭代。请帮忙。

标签: javajsonstringparsingdeeppavlov

解决方案


它取决于您用来反序列化字符串的库。看来您正在使用 org json 代码,因此可能的解决方案使用JSONTokener

将 JSON (RFC 4627) 编码的字符串解析为相应的对象

然后使用方法nextValue

从输入中返回下一个值。可以是 JSONObject、JSONArray、String、Boolean、Integer、Long、Double 或 JSONObject#NULL。

代码如下

Object jsonObject = new JSONTokener(jsonAsString).nextValue();

推荐阅读