使用gson从Android上的URL读取简单的JSON

时间:2017-11-12 16:29:24

标签: java android json gson

我试图从一个看起来像这样的URL(https://link.com/json.php)中读取非常简单的JSON

{
    "code":"asdfg"
}

我在网上尝试了很多文章,这就是我能做的,但是它没有成功运行并且崩溃了Android应用程序。有什么我做错了吗?

static class Page {
String code;
}

public static String checkIp() throws Exception {
String json = readUrl("https://link.com/json.php");
Gson gson = new Gson();
Page page = gson.fromJson(json, Page.class);
Log.d("MainActivity", page.code);
return (page.code);
}

private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
    URL url = new URL(urlString);
    reader = new BufferedReader(new InputStreamReader(url.openStream()));
    StringBuffer buffer = new StringBuffer();
    int read;
    char[] chars = new char[1024];
    while ((read = reader.read(chars)) != -1)
        buffer.append(chars, 0, read);

    return buffer.toString();
} finally {
    if (reader != null)
        reader.close();
}
}

错误:

FATAL EXCEPTION: main
   Process: com.a.b.c, PID: 26961
   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.a.b.c/com.a.b.c.MainActivity}: android.os.NetworkOnMainThreadException
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
       at android.app.ActivityThread.-wrap12(ActivityThread.java)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:154)
       at android.app.ActivityThread.main(ActivityThread.java:6123)
       at java.lang.reflect.Method.invoke(Native Method)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
    Caused by: android.os.NetworkOnMainThreadException
       at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1317)
       at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86)
       at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
       at java.net.InetAddress.getAllByName(InetAddress.java:752)
       at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
       at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:187)
       at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:156)
       at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:98)
       at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:345)
       at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:328)
       at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
       at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
       at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:405)
       at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:243)
       at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
       at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
       at com.a.b.c.MainActivity.parseJson(MainActivity.java:64)
       at com.a.b.c.MainActivity.onCreate(MainActivity.java:54)
       at android.app.Activity.performCreate(Activity.java:6672)
       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) 
       at android.app.ActivityThread.-wrap12(ActivityThread.java) 
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) 
       at android.os.Handler.dispatchMessage(Handler.java:102) 
       at android.os.Looper.loop(Looper.java:154) 
       at android.app.ActivityThread.main(ActivityThread.java:6123) 
       at java.lang.reflect.Method.invoke(Native Method) 
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) 

1 个答案:

答案 0 :(得分:0)

要在android中使用GSON,请记得在build.gradle上提供它

dependencies {
    compile 'com.google.code.gson:gson:2.8.2'
}

您的GSON代码

static class Page {
    String code;
}

public static String checkIp() throws Exception {
    String json = readUrl("https://link.com/json.php");

    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();

    Page page = gson.fromJson(json, Page.class);
    Log.d("MainActivity", page.code);
    return Page.code;
}

我刚修改了你的GSON代码。您的以下方法readURL是您自己的。我希望这个方法没有问题。我通常使用Volley Library来解析JSON。如果您进一步遇到任何问题,可以使用任何HTTP请求库,如Volley。