Java获取JSON文件,我哪里做错了?

时间:2015-07-31 15:52:40

标签: java android json exception

我是Android开发和Java的新手,我是C#开发人员。我不能通过这个调试。我试图让System.out.println吐出异常消息和堆栈跟踪,但由于某种原因它们不起作用。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.Date;
import java.net.URL;
import org.json.JSONObject;

public class Weather {

public Base Base = new Base();
public Cloud Cloud = new Cloud();
public Coord Coord = new Coord();
public Info Info = new Info();
public Location Location = new Location();
public Temperature Temperature = new Temperature();
public Wind Wind = new Wind();

public Boolean fetch(String location) {

    try {

        String urlString = "http://api.openweathermap.org/data/2.5/weather?q=" + location + "&units=metric";
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        BufferedReader reader = new BufferedReader( new InputStreamReader ( connection.getInputStream() ) );
        StringBuffer json = new StringBuffer(1024);
        String tmp = "";
        while ( ( tmp = reader.readLine() ) != null )
            json.append(tmp).append("\n");
        reader.close();
        JSONObject data = new JSONObject( json.toString() );
        if (data.getInt("cod") != 200) {

            throw new Exception("cod is not 200");

        } else {

            Base.base = data.getString("base");

            Cloud.Value = data.getJSONObject("clouds").getInt("all");

            Coord.lat = data.getJSONObject("coord").getDouble("lat");
            Coord.lon = data.getJSONObject("coord").getDouble("lon");

            // Array Processing
            JSONObject id = data.getJSONArray("weathr").getJSONObject(0);
            JSONObject main = data.getJSONArray("weather").getJSONObject(1);
            JSONObject description = data.getJSONArray("weather").getJSONObject(2);
            JSONObject icon = data.getJSONArray("weather").getJSONObject(3);

            Info.description = description.getString("description");
            Info.icon = icon.getString("icon");
            Info.id = id.getInt("id");
            Info.main = main.getString("main");

            Location.cod = data.getInt("cod");
            Location.dt = new Date((long) data.getInt("dt") * 1000);
            Location.country = data.getJSONObject("sys").getString("country");
            Location.id = data.getInt("id");
            Location.message = data.getJSONObject("sys").getDouble("message");
            Location.name = data.getString("name");
            Location.sunrise = new Date((long) data.getJSONObject("sys").getInt("sunrise"));
            Location.sunset = new Date((long) data.getJSONObject("sys").getInt("sunset"));

            Temperature.humidity = data.getJSONObject("main").getInt("humidity");
            Temperature.max = data.getJSONObject("main").getInt("temp_max");
            Temperature.min = data.getJSONObject("main").getInt("temp_min");
            Temperature.pressure = data.getJSONObject("main").getInt("pressure");
            Temperature.temp = data.getJSONObject("main").getInt("temp");

            Wind.deg = data.getJSONObject("wind").getInt("deg");
            Wind.speed = data.getJSONObject("wind").getDouble("speed");

        }

        return true;        

    } catch (Exception ex) {

        System.out.println("Mayday, " + ex.getMessage().toString() +  ex.getStackTrace().toString());
        return false;

    }
}

那么,我该如何解决这个问题,你能否提供更好的调试方法..

更新: - 我得到了StackTrace,但我无法理解错误发生的原因。你能解释一下吗

08-01 00:41:05.010: W/System.err(8557): android.os.NetworkOnMainThreadException
08-01 00:41:05.010: W/System.err(8557):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
08-01 00:41:05.010: W/System.err(8557):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-01 00:41:05.010: W/System.err(8557):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-01 00:41:05.010: W/System.err(8557):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
08-01 00:41:05.020: W/System.err(8557):     at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
08-01 00:41:05.020: W/System.err(8557):     at antu.mango.weather.Weather.fetch(Weather.java:27)
08-01 00:41:05.020: W/System.err(8557):     at antu.mango.drizzle.MainActivity.onCreate(MainActivity.java:26)

2 个答案:

答案 0 :(得分:2)

不要手动打印出堆栈跟踪,请尝试以下方法:

ex.printStackTrace();

这将为您提供一个逐个注释的逐行注释错误消息,说明发生了什么。

此外,将所有内容放在一个巨大的try / catch块中真的是非常糟糕的做法。尝试将代码分解为逻辑块并尝试/捕获每个代码,以便在错误检查时更精细。

答案 1 :(得分:0)

如果您正在开发Android,我建议您使用

Log.d("SOME TEXT", data_to_analyze);

就像System.out.print(data_to_analyze);,但在Android中。 你可以在android Logcat

中看到你想要的东西