将BufferedReader转换为JSONObject(json-simple)

huangapple go评论64阅读模式
英文:

Convert Buffered Reader in JSONObject (json-simple)

问题

我正在以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

非常感谢。

英文:

i'm calling a Rest API in GET, and i need to parse the response and take the value of a key.
I'm using:

&lt;dependency&gt;
            &lt;groupId&gt;com.googlecode.json-simple&lt;/groupId&gt;
            &lt;artifactId&gt;json-simple&lt;/artifactId&gt;
            &lt;version&gt;1.1.1&lt;/version&gt;
        &lt;/dependency&gt;

This is my code:

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();

But in JSONObject jsonObject = new JSONObject(sb.toString()); generate a error
Error:(32, 63) java: incompatible types: java.lang.String cannot be converted to java.util.Map

Thanks so much.

答案1

得分: 1

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

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

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

英文:

You should be using JSONParser to get the data from String:

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

JSONObject is used to serialize its data into JSON string via toJSONString() method.

huangapple
  • 本文由 发表于 2020年5月5日 01:51:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/61598521.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定