繁体   English   中英

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

[英]Unable to show json data from URL with java

我有一个问题,我不知道如何解决。

我有以下代码:

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,发现了很多响应,但是没有一个对我有用。

编辑:我更新了代码,并使用了完整的main和下面的内容,您可以看到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
}

预先感谢您的帮助。

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

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

        }
    }

}

我不太确定“显示为列表”的意思。 如果我正确理解了您的问题,我认为存储和显示数据的最佳方法是在从响应中获取原始数据之后,能够解析并将JSON数据转换为Java Object。

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

放置好Java对象后,就可以使用任何JSON libaray进行从JSON到Java Object的转换。

这是一个使用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;
}

}

假设

  • 所有GET服务调用响应的JSON架构都是相同的。

希望这对我的朋友有帮助。

暂无
暂无

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

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