简体   繁体   English

如何将字符串转换为 JsonObject

[英]How to convert a String to a JsonObject

I am using a HttpURLConnection to get Json from a web into a string.我正在使用HttpURLConnectionJson从网络获取到字符串中。

And i'm storing web string into BufferedReader and after that storing it in a new String .我将 web 字符串存储到BufferedReader ,然后将其存储在一个新的String

And string is here:-字符串在这里:-

{"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}

How can i convert it into JsonObject.如何将其转换为 JsonObject。

I've also seen this answer ( How to convert String to JsonObject ) but it's not working.我也看过这个答案( How to convert String to JsonObject )但它不起作用。

Here is code:-这是代码:-

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

Here output is the String which I've mentioned it earlier.这里的输出是我之前提到的字符串。 I'm not getting the Output Cityname in my console.我没有在控制台中获得输出城市名称。

Use this library.使用这个库。 It provides very simple API, to convert a String to json object simply do the following:它提供了非常简单的 API,将 String 转换为 json 对象只需执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM