3
A few days ago I asked for help here in the OS to parse JSON in Java and I got what I wanted, however, I had to do a "gambiarra" by not knowing a better way.
It’s working, but I’m sure the code can be improved.
my JSON is as follows:
"weather": [
{
"id": 800,
"main": "Clear",
"description": "tempo claro",
"icon": "01n" }
],
"main": {
"temp": 16.29,
"pressure": 1020,
"humidity": 77,
"temp_min": 16.29
},
my exit is
O tempo está: tempo claro
A temperatura neste momento é de 16.29º
and the code to generate my output was as follows
JSONObject condicao = obj.getJSONArray("weather").getJSONObject(0);
escritor.println("O tempo está: " + condicao.getString("description"));
String n = obj.getString("main");
String t [] = n.split(Pattern.quote (","));
String x = t[0];
escritor.println("A temperatura neste momento é de " + x.substring(8,13) + "º");
As you can see I couldn’t isolate the category fields main since they were all in one String only.
So I created several auxiliary strings to split, separate what I wanted to display and then cut the characters that I didn’t want to be printed.
Could you tell me how to do this in a more practical way?
Thank you
Exact. Basically the friend did not know that it is possible to access a nested object through the method
getJSONObject.– Gabriel
Thank you, Isaac. The code passed by you presented problem with the
getDoublewhich, according to Netbeans does not exist in the class, but I resolved withmainObj.get("temp")ormainObj.getString("temp"). I say this so you can edit the answer and help more people with the same question. P.S. my JSON library used is theTwitter4jsince I am also implementing integration with the social network API in the application– Evilmaax
@You’re welcome. I assumed you were using org.json and so it didn’t match/work with the library you were using. Thank you for warning, that so I have updated the response to contemplate both solutions.
– Isac