0

I have a problem and I can't figure out how to solve it.

I have the following code:

public static void main(String[] args) 
{
    BufferedReader br = null;
    StringBuilder sb = null;
    String line = null;
    Scanner scanner = new Scanner(System.in);


    //print the menu
    System.out.println("Choose from the menu:");
    System.out.println("1 -> Town weather ");
    System.out.println("2 -> About");
    System.out.println("3 -> Exit");

    try 
    {
        //read from keyboard the value
        //int choice = scanner.nextInt();
        int choice = 1;

        switch (choice)
        {
            case 1:
                System.out.println("Give desired town:");
                String town = str.nextLine();
                URL json = new URL("http://api.openweathermap.org/data/2.5/weather?q=" + town + "&APPID=");
                HttpURLConnection url = (HttpURLConnection) json.openConnection();

                url.setRequestMethod("GET");
                url.connect();

                //read the data from url
                br = new BufferedReader(new InputStreamReader(url.getInputStream()));
                sb = new StringBuilder();

                while ((line = br.readLine()) != null)
                {
                    sb.append(line + '\n'); 
                }                   

                String txt = sb.toString();

                break;

            case 2:
                break;

            case 3:
                System.exit(0);         
        }
    }
    catch (InputMismatchException i)
    {
        System.out.println("Wrong choice!");
    }
    catch (MalformedURLException m)
    {
        System.out.println("Wrong URL!");
    }
    catch (IOException io)
    {
        System.out.println("Wrong town! The url shows 404 not found");
    }
    catch (NullPointerException np)
    {
        System.out.println("Null exception!");
        np.printStackTrace();
    }
    catch (Exception e) //catch all exception where not previous caught.
    {
        e.printStackTrace();
    }
}

So I have the json data into txt variable. The problem is, that my project requires to show all the data (or a part of them), as a list. I must show them in such a way that a human can read them.

I tried pretty printing, but I do not want to show the symbols { } , :

Ideally, I would like to store these data into a database and then show some of them, while I maintain them. The first step, is to split them, in an array, only the strings and none of the special characters.

Can anyone help me with this? I searched stackoverflow, and I found many responses, but none worked for me.

EDIT: I updated the code, with my full main and below you can see the json response:

{
  "coord": {
    "lon": -86.97,
    "lat": 34.8
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 270.48,
    "pressure": 1033,
    "humidity": 30,
    "temp_min": 270.15,
    "temp_max": 271.15
  },
  "visibility": 16093,
  "wind": {
    "speed": 2.6,
    "deg": 340
  },
  "clouds": {
    "all": 1
  },
  "dt": 1514921700,
  "sys": {
    "type": 1,
    "id": 226,
    "message": 0.0021,
    "country": "US",
    "sunrise": 1514897741,
    "sunset": 1514933354
  },
  "id": 4830668,
  "name": "Athens",
  "cod": 200
}

Thank you in advance for your help.

2 Answers 2

1

Try below code to convert your response to json object,which you can convert to desired format or persist to DB later on

package test;

import javax.net.ssl.HttpsURLConnection;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {

    String url="your URL"
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpget = new HttpGet(url);
    HttpResponse httpResponse  = httpClient.execute(httpget);


    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        //read response from body
        ResponseHandler<String> handler = new BasicResponseHandler();
        String respBody = handler.handleResponse(httpResponse);
        if (respBody != null && !"".equals(respBody)) {
            JsonObject responseJson =  new 
        JsonParser().parse(respBody).getAsJsonObject();

        }
    }

}
Sign up to request clarification or add additional context in comments.

1 Comment

the DefaultHttpClient is shown as deprecated and it doesn't work. I would like to show them as a list (the insertion to the DB, will be completed afterwards): Town: ... Country: ...
0

I am not so sure what you mean by show "as a list". If I understand your question correctly, I think the best way to store and show the data is to be able to parse and cast the JSON data into a Java Object after you fetch the raw data from the response.

First step is to figure out what the JSON schema looks like and then extract/create a Java Object out of it. You can easily accomplish this using jar or lib or you can also do it do it online by copying and pasting the raw JSON into http://www.jsonschema2pojo.org/ and it will let you download a zip file that contains all the Java Objects needed for casting.

Once you have the Java Object in place, then you can use any JSON libaray to do the casting from and to the JSON to Java Object.

Here is a simple casting example using Gson library :

String txt = sb.toString();
Gson gson = new Gson();
Container jsonDataHolder = new Container();

try{
    jsonDataHolder = gson.fromJson(txt , Container.class);
} catch (IllegalStateException e) {
    e.printStackTrace();
} catch (JsonSyntaxException e) {
    e.printStackTrace();
}

// Finally don't forget to close BufferedReader.close()


// After Casting is completed, you can pretty much do anything with the object.

System.out.println("City Name : " + jsonDataHolder.getName())

// Below is the individual Java Object classes that are required to do the full scope casting of the JSON object you've provided. 


public class Container {

    @SerializedName("coord")
    @Expose
    private Coord coord;
    @SerializedName("weather")
    @Expose
    private List<Weather> weather = null;
    @SerializedName("base")
    @Expose
    private String base;
    @SerializedName("main")
    @Expose
    private Main main;
    @SerializedName("visibility")
    @Expose
    private Integer visibility;
    @SerializedName("wind")
    @Expose
    private Wind wind;
    @SerializedName("clouds")
    @Expose
    private Clouds clouds;
    @SerializedName("dt")
    @Expose
    private Integer dt;
    @SerializedName("sys")
    @Expose
    private Sys sys;
    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("cod")
    @Expose
    private Integer cod;

    public Coord getCoord() {
        return coord;
    }

    public void setCoord(Coord coord) {
        this.coord = coord;
    }

    public List<Weather> getWeather() {
        return weather;
    }

    public void setWeather(List<Weather> weather) {
        this.weather = weather;
    }

    public String getBase() {
        return base;
    }

    public void setBase(String base) {
        this.base = base;
    }

    public Main getMain() {
        return main;
    }

    public void setMain(Main main) {
        this.main = main;
    }

    public Integer getVisibility() {
        return visibility;
    }

    public void setVisibility(Integer visibility) {
        this.visibility = visibility;
    }

    public Wind getWind() {
        return wind;
    }

    public void setWind(Wind wind) {
        this.wind = wind;
    }

    public Clouds getClouds() {
        return clouds;
    }

    public void setClouds(Clouds clouds) {
        this.clouds = clouds;
    }

    public Integer getDt() {
        return dt;
    }

    public void setDt(Integer dt) {
        this.dt = dt;
    }

    public Sys getSys() {
        return sys;
    }

    public void setSys(Sys sys) {
        this.sys = sys;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getCod() {
        return cod;
    }

    public void setCod(Integer cod) {
        this.cod = cod;
    }

}




 public class Coord {

    @SerializedName("lon")
    @Expose
    private Double lon;
    @SerializedName("lat")
    @Expose
    private Double lat;

    public Double getLon() {
        return lon;
    }

    public void setLon(Double lon) {
        this.lon = lon;
    }

    public Double getLat() {
        return lat;
    }

    public void setLat(Double lat) {
        this.lat = lat;
    }

}





public class Main {

@SerializedName("temp")
@Expose
private Double temp;
@SerializedName("pressure")
@Expose
private Integer pressure;
@SerializedName("humidity")
@Expose
private Integer humidity;
@SerializedName("temp_min")
@Expose
private Double tempMin;
@SerializedName("temp_max")
@Expose
private Double tempMax;

public Double getTemp() {
    return temp;
}

public void setTemp(Double temp) {
    this.temp = temp;
}

public Integer getPressure() {
    return pressure;
}

public void setPressure(Integer pressure) {
    this.pressure = pressure;
}

public Integer getHumidity() {
    return humidity;
}

public void setHumidity(Integer humidity) {
    this.humidity = humidity;
}

public Double getTempMin() {
    return tempMin;
}

public void setTempMin(Double tempMin) {
    this.tempMin = tempMin;
}

public Double getTempMax() {
    return tempMax;
}

public void setTempMax(Double tempMax) {
    this.tempMax = tempMax;
}

}






public class Wind {

@SerializedName("speed")
@Expose
private Double speed;
@SerializedName("deg")
@Expose
private Integer deg;

public Double getSpeed() {
    return speed;
}

public void setSpeed(Double speed) {
    this.speed = speed;
}

public Integer getDeg() {
    return deg;
}

public void setDeg(Integer deg) {
    this.deg = deg;
}

}



public class Clouds {

@SerializedName("all")
@Expose
private Integer all;

public Integer getAll() {
    return all;
}

public void setAll(Integer all) {
    this.all = all;
}

}



public class Sys {

@SerializedName("type")
@Expose
private Integer type;
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("message")
@Expose
private Double message;
@SerializedName("country")
@Expose
private String country;
@SerializedName("sunrise")
@Expose
private Integer sunrise;
@SerializedName("sunset")
@Expose
private Integer sunset;

public Integer getType() {
    return type;
}

public void setType(Integer type) {
    this.type = type;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public Double getMessage() {
    return message;
}

public void setMessage(Double message) {
    this.message = message;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public Integer getSunrise() {
    return sunrise;
}

public void setSunrise(Integer sunrise) {
    this.sunrise = sunrise;
}

public Integer getSunset() {
    return sunset;
}

public void setSunset(Integer sunset) {
    this.sunset = sunset;
}

}

Assumption:

  • The JSON Schema is the same for all the GET service call response.

Hope this helps my friend.

2 Comments

I updated my code and the response. I would like to show something like, Town: Athens (the town will be inserted by the user) Country: US
I've updated the answer based on your latest updated question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.