【问题标题】:Java get JSON file, Where did I do wrong?Java获取JSON文件,我哪里做错了?
【发布时间】:2015-07-31 15:52:39
【问题描述】:

我是 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)

【问题讨论】:

标签: java android json exception


【解决方案1】:

与其尝试手动打印堆栈跟踪,不如试试这个:

ex.printStackTrace();

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

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

【讨论】:

  • 好的,我试过了。现在我知道错误在哪里。但原因是为什么会出现这个错误......它在“BufferedReader reader”。我已经更新了问题
  • 如果你google NetworkOnMainThread异常,你会发现这意味着你不能在Android的主线程上做任何与网络相关的任务。这是防止网络阻塞 GUI 的不良做法的保障措施。您要做的是学习如何使用 AsyncTask。再一次,谷歌它,android API 文档非常好。
【解决方案2】:

如果你是安卓开发,我推荐你使用

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

类似于System.out.print(data_to_analyze);,但在 Android 中。 你可以在android中看到你想要的Logcat

【讨论】: