How to improve this code

3

Some 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" for 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 output 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 could not isolate the fields from the main category since they were all in a String only.

So I created several auxiliary strings to split, separate what I wanted to display, and then cut the characters I did not want to be printed.

Could you tell me how to do this in a more practical way?

Thank you

    
asked by anonymous 12.12.2017 / 03:05

1 answer

4

Since it has a JSON it will be ideal to navigate all information through the methods of the JSON parser instead of using regexs and / or splits.

Using org.json

The most direct way to get the temperature, which is in this case the temp property of your JSON, would be:

  • First access object main with getJSONObject
  • On this object, you can now access the temp field with getDouble

Applying to your code:

JSONObject condicao = obj.getJSONArray("weather").getJSONObject(0);
System.out.println("O tempo está: " + condicao.getString("description"));
JSONObject mainObj = obj.getJSONObject("main"); //como JSONObject e não String
System.out.println("A temperatura neste momento é de " + mainObj.getDouble("temp") + "º");

Using twitter4j

Although the logic to apply to this library is the same, there is in fact no method getDouble that gets the value directly as Double .

You can instead use the get method that returns a Object and that in case the value to be interpreted is a decimal number this object will be Double , having almost the same effect as the getDouble of org.json .

So just the last line needs to be different:

System.out.println("A temperatura neste momento é de " + mainObj.get("temp") + "º");
    
12.12.2017 / 04:20