【问题标题】:Convert Buffered Reader in JSONObject (json-simple)在 JSONObject 中转换缓冲阅读器(json-simple)
【发布时间】:2020-05-04 17:51:21
【问题描述】:

我在 GET 中调用了一个 Rest API,我需要解析响应并获取一个键的值。 我正在使用:

<dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>

这是我的代码:

if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder sb = new StringBuilder();
            while ((readLine = in.readLine()) != null) {
                sb.append(readLine);
            }
            JSONObject jsonObject = new JSONObject(sb.toString());
            jsonObject.get();
            in.close();

但是在JSONObject jsonObject = new JSONObject(sb.toString()); 生成错误 错误:(32, 63) java: 不兼容的类型:java.lang.String 无法转换为 java.util.Map

非常感谢。

【问题讨论】:

    标签: java json parsing json-simple rest


    【解决方案1】:

    您应该使用JSONParser 从字符串中获取数据:

    JSONParser parser = new JSONParser(); 
    JSONObject json = (JSONObject) parser.parse(sb.toString());
    

    JSONObject用于通过toJSONString()方法将其数据序列化为JSON字符串。

    【讨论】:

    • 非常感谢。如果现在我想取值,怎么办,我尝试了 json.get('key1') 但没有,结构是这样的 {status:200 data:{key1:value,key2:value}},我想获取 key1 :价值。非常感谢
    • 你需要先得到data对象,然后再把key1取出来:String v1 = ((JSONObject)simpleJson.get("data")).get("key1").toString();
    • 我是这样做的,而且工作...JSONObject json = (JSONObject) parser.parse(sb.toString()); JSONObject jsonData = (JSONObject) json.get("data"); String stringTranslated = (String) jsonData.get("translation");
    猜你喜欢
    • 2014-02-22
    • 2023-03-28
    • 2015-02-06
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多