如何从Get Json Raw File更改为Json Url?

时间:2017-09-01 13:00:18

标签: android json

我有一个正常的代码:从原始文件中获取Json(raw / video_list.json)

public class VideoListFragment extends BaseListFragment {

VideoAdapter adapter;
@Override
protected RecyclerView.Adapter getAdapter() {
    if (adapter == null) {
        String jsonStr = readRawFile();
        Gson gson = new Gson();
        VideoPage videoPage = gson.fromJson(jsonStr, VideoPage.class);
        adapter = new VideoAdapter(videoPage);
    }
    return adapter;
}

String readRawFile() {
    String content = "";
    Resources resources = getContext().getResources();
    InputStream is = null;
    try {
        is = resources.openRawResource(R.raw.video_list);
        byte buffer[] = new byte[is.available()];
        is.read(buffer);
        content = new String(buffer);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return content;
}
}

现在我想从Url获​​取Json,我将video_list.json文件中的Json复制到myjson.com,然后获取url(https://api.myjson.com/bins/uyzbl),我更改代码:

public class VideoListFragment extends BaseListFragment {
VideoAdapter adapter;
@Override
protected RecyclerView.Adapter getAdapter() {
    if (adapter == null) {
        String jsonStr = readData("https://api.myjson.com/bins/71535");
        Gson gson = new Gson();
        VideoPage videoPage = gson.fromJson(jsonStr, VideoPage.class);
        adapter = new VideoAdapter(videoPage);
    }
    return adapter;
}
String readData(String url) {
    HttpsURLConnection con = null;
    try {
        URL u = new URL(url);
        con = (HttpsURLConnection) u.openConnection();
        con.connect();
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        return sb.toString();

    } catch (MalformedURLException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (con != null) {
            try {
                con.disconnect();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    return null;
}
}

Android Studio中没有发生错误,但不幸的是,App停止了。你能帮我找到并解决它吗?

0 个答案:

没有答案