无法使用java显示URL中的json数据

时间:2018-01-02 19:12:33

标签: java json parsing

我遇到了问题,我无法弄清楚如何解决它。

我有以下代码:

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

所以我将json数据转换为txt变量。问题是,我的项目需要以列表的形式显示所有数据(或其中的一部分)。我必须以人类可以阅读它们的方式展示它们。

我尝试过漂亮的打印,但我不想显示符号{},:

理想情况下,我想将这些数据存储到数据库中,然后显示其中一些数据,同时保留它们。第一步是将它们分成数组,只分割字符串而不分割任何特殊字符。

任何人都可以帮我吗?我搜索了stackoverflow,我发现了许多回复,但没有一个对我有效。

编辑:我更新了代码,用我的完整主文件和下面的内容你可以看到json响应:

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

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

尝试下面的代码将您的响应转换为json对象,您可以将其转换为所需的格式,或稍后继续保存到DB

FOR

答案 1 :(得分:0)

我不太确定你的意思是什么?#34;作为一个清单"。如果我正确理解您的问题,我认为存储和显示数据的最佳方法是在从响应中获取原始数据后,能够将JSON数据解析并转换为Java对象。

第一步是弄清楚JSON模式的样子,然后从中提取/创建Java Object。您可以使用jar或lib轻松完成此操作,或者您也可以通过将原始JSON复制并粘贴到http://www.jsonschema2pojo.org/来在线完成此操作,它将允许您下载包含所有转换所需的Java对象的zip文件。

一旦有了Java对象,就可以使用任何JSON libaray从JSON到Java对象进行转换。

这是一个使用Gson库的简单演示示例:

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

}

<强>假设

  • JSON Schema与所有GET服务调用响应相同。

希望这有助于我的朋友。