java - 如何将字符串转换为 JsonObject

标签 java json

我正在使用 HttpURLConnectionJson 从网络获取到字符串。

我将网络字符串存储到 BufferedReader 中,然后将其存储在新的 String 中。

字符串在这里:-

{"coord":{"lon":72.85,"lat":19.01},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"base":"stations","main":{"temp":302.131,"pressure":1024.24,"humidity":84,"temp_min":302.131,"temp_max":302.131,"sea_level":1024.75,"grnd_level":1024.24},"wind":{"speed":4.77,"deg":302.001},"clouds":{"all":12},"dt":1459677392,"sys":{"message":0.0102,"country":"IN","sunrise":1459645229,"sunset":1459689786},"id":1275339,"name":"Mumbai","cod":200}

如何将其转换为 JsonObject。

我也看到了这个答案( How to convert String to JsonObject ),但它不起作用。

这是代码:-

    BufferedReader br= new BufferedReader(new InputStreamReader(conn.getInputStream()));

    String localoutput;
    while ((localoutput = br.readLine()) != null) 
    {
            output=localoutput+output;
    }
    conn.disconnect();
    }
    catch(Exception e)
    {
        System.out.println(e);  
    }

JsonReader jsonReader = Json.createReader(new StringReader(output));
JsonObject object = jsonReader.readObject();
jsonReader.close();

try {
    String cityname = object.getString("name");
    System.out.println(cityname);
} 
catch (Exception e)
{
    e.printStackTrace();
}

这里的输出是我之前提到的字符串。 我没有在控制台中获取输出城市名称。

最佳答案

使用this图书馆。它提供了非常简单的 API,将 String 转换为 json 对象只需执行以下操作:

try {
    JSONObject object = new JSONObject(yourJsonString);
} catch (Exception e){
    e.printStackTrace();
}

关于java - 如何将字符串转换为 JsonObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36384225/

相关文章:

php - 安卓、PHP、HttpGet

java - 无法使用 Eclipse 上的最新更新修改属性

java - append 到 HDFS 中的现有文件时出现异常

java - JasperReports 需要 Jars 吗?

java - @RequestBody 不适用于 Rest 服务

jquery - 使用 jquery 和 Json 时日期值显示格式错误

javascript - 将多个 JSON 文件中的键和值附加到一个 JSON 对象

Java将Hashmap放入Treemap

java - 如何修复此错误 :"Attempted to serialize java.lang.Class: org.springframework.beans.factory.annotation.Qualifier"

java - ReSTLet客户端如何处理媒体类型的请求?