将BufferedReader转换为JSONObject(json-simple)

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

Convert Buffered Reader in JSONObject (json-simple)

问题

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

  1. <dependency>
  2. <groupId>com.googlecode.json-simple</groupId>
  3. <artifactId>json-simple</artifactId>
  4. <version>1.1.1</version>
  5. </dependency>

这是我的代码:

  1. if (responseCode == HttpURLConnection.HTTP_OK) {
  2. BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  3. StringBuilder sb = new StringBuilder();
  4. while ((readLine = in.readLine()) != null) {
  5. sb.append(readLine);
  6. }
  7. JSONObject jsonObject = new JSONObject(sb.toString());
  8. jsonObject.get();
  9. 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:

  1. &lt;dependency&gt;
  2. &lt;groupId&gt;com.googlecode.json-simple&lt;/groupId&gt;
  3. &lt;artifactId&gt;json-simple&lt;/artifactId&gt;
  4. &lt;version&gt;1.1.1&lt;/version&gt;
  5. &lt;/dependency&gt;

This is my code:

  1. if (responseCode == HttpURLConnection.HTTP_OK) {
  2. BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  3. StringBuilder sb = new StringBuilder();
  4. while ((readLine = in.readLine()) != null) {
  5. sb.append(readLine);
  6. }
  7. JSONObject jsonObject = new JSONObject(sb.toString());
  8. jsonObject.get();
  9. 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 从字符串中获取数据:

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

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

英文:

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

  1. JSONParser parser = new JSONParser();
  2. 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:

确定