解析在Android应用程序一个JSON文件(Parsing a JSON file in Andr

2019-10-29 14:09发布

我有一个JSON文件看起来像这样:

{
e:"_caIUfOJIo3FPeOwgOAI",
c:0,
u:"https://www.google.com.tr/complete/search?client\x3dhp\x26hl\x3den\x26sugexp\x3dernk_ir\x26gs_rn\x3d8\x26gs_ri\x3dhp\x26tok\x3dVepIjB5Y4hHneLHcIO5AsQ\x26cp\x3d9\x26gs_id\x3d1sy\x26xhr\x3dt\x26q\x3damerica%20is\x26tch\x3d1\x26ech\x3d1\x26psi\x3dFW9kUZu1J6Sw0QXLyIHgBg.1365536538389.1",
p:true,
d:"[
    \x22america is\x22,
        [
            [\x22america is\\u003Cb\\u003E doomed\\u003C\\/b\\u003E\x22,0,[]],
            [\x22america is\\u003Cb\\u003E in the heart\\u003C\\/b\\u003E\x22,0,[]],
            [\x22america is\\u003Cb\\u003E evil\\u003C\\/b\\u003E\x22,0,[]],
            [\x22america is\\u003Cb\\u003E not a christian nation\\u003C\\/b\\u003E\x22,0,[]],
            [\x22america is\\u003Cb\\u003E not the greatest country\\u003C\\/b\\u003E\x22,0,[]],
            [\x22america is\\u003Cb\\u003E in the heart summary\\u003C\\/b\\u003E\x22,0,[]],
            [\x22america is\\u003Cb\\u003E dying\\u003C\\/b\\u003E\x22,0,[]],
            [\x22america is\\u003Cb\\u003E falling apart\\u003C\\/b\\u003E\x22,0,[]],
            [\x22america is\\u003Cb\\u003E all about speed\\u003C\\/b\\u003E\x22,0,[]],
            [\x22america is\\u003Cb\\u003E in the heart sparknotes\\u003C\\/b\\u003E\x22,0,[]]
        ],
        {\x22j\x22:\x221sy\x22,\x22q\x22:\x22f87KpN3GEzebiGEgM8LiN37wsQc\x22,\x22t\x22:{\x22bpc\x22:false,\x22tlw\x22:false}}
    ]
    "}/*""*/

我想解析像是“心脏”“在劫难逃”,“神雕侠侣”等字符串,但我是新来的Android和JSON解析两者。 所以,请你能请我有关分析这种JSON的进步。 这里是我的功能如下:

@SuppressWarnings("null")
    public String[] parseJSON(String URL)
    {
        String[] finals = null;
        JSONArray results = null;
        String TAG_RESULTS = "d";

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(URL);

        try {
            results = json.getJSONArray(TAG_RESULTS);
            JSONArray tenResults = results.getJSONArray(0);  

            for(int i = 0; i < tenResults.length(); i++){
                JSONArray c = tenResults.getJSONArray(i);
                String content = c.toString();
                content.substring(content.indexOf("\\u003Cb\\u003E ")+"\\u003Cb\\u003E ".length(), content.indexOf("\\u003C\\/b"));
                finals[i] = content;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return finals;
    } 

我试着调试应用程序,但我不能因为一些源文件丢失的错误,我不能做的意义伸入try块。 据我所看到的,它成功地创建JSONParser对象。

编辑:logcat

05-07 12:17:02.562: E/AndroidRuntime(6007): FATAL EXCEPTION: main
05-07 12:17:02.562: E/AndroidRuntime(6007): java.lang.IllegalStateException: Could not execute method of the activity
05-07 12:17:02.562: E/AndroidRuntime(6007):     at android.view.View$1.onClick(View.java:3597)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at android.view.View.performClick(View.java:4202)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at android.view.View$PerformClick.run(View.java:17340)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at android.os.Handler.handleCallback(Handler.java:725)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at android.os.Handler.dispatchMessage(Handler.java:92)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at android.os.Looper.loop(Looper.java:137)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at android.app.ActivityThread.main(ActivityThread.java:5039)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at java.lang.reflect.Method.invokeNative(Native Method)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at java.lang.reflect.Method.invoke(Method.java:511)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at dalvik.system.NativeStart.main(Native Method)
05-07 12:17:02.562: E/AndroidRuntime(6007): Caused by: java.lang.reflect.InvocationTargetException
05-07 12:17:02.562: E/AndroidRuntime(6007):     at java.lang.reflect.Method.invokeNative(Native Method)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at java.lang.reflect.Method.invoke(Method.java:511)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at android.view.View$1.onClick(View.java:3592)
05-07 12:17:02.562: E/AndroidRuntime(6007):     ... 11 more
05-07 12:17:02.562: E/AndroidRuntime(6007): Caused by: android.os.NetworkOnMainThreadException
05-07 12:17:02.562: E/AndroidRuntime(6007):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at com.example.googlesearch.JSONParser.getJSONFromUrl(JSONParser.java:38)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at com.example.googlesearch.AuxilaryVerbs.parseJSON(AuxilaryVerbs.java:39)
05-07 12:17:02.562: E/AndroidRuntime(6007):     at com.example.googlesearch.AuxilaryVerbs.is_clicked(AuxilaryVerbs.java:81)
05-07 12:17:02.562: E/AndroidRuntime(6007):     ... 14 more
05-07 12:17:02.572: D/dalvikvm(6007): GC_CONCURRENT freed 439K, 9% free 5623K/6176K, paused 3ms+0ms, total 6ms

Answer 1:

d:"[ ... ]"不是一个JSONArray而是一个String

您需要获得该字符串,并再次解析成JSON。



Answer 2:

为什么不能让生活更简单的自己,并使用GSON ? 基于您的代码我敲了一个快速的示例:

创建一个POJO来表示你的模型:

public class Result {

    @SerializedName("e")
    public String e;

    @SerializedName("c")
    public int c;

    @SerializedName("u")
    public String u;

    @SerializedName("p")
    public boolean p;

    @SerializedName("d")
    public String[] d;

}

现在从JSON字符串创建一个实例。

String json = "//some json string//";
Gson gson = new Gson();
Result result = gson.fromJson(json, Result.class);

//do something with result
if(result.p)
{
  //argh we have a "p"
}

//or maybe we iterate over the strings you were after
for(String myString : result.d)
{
    //do something with myString which might be set to "evil" etc
}


Answer 3:

我认为你必须在该字符串的问题:

String[] finals = null;

不创建字符串数组但在循环使用:

finals[i] = content;

在这种情况下,我可以reccomend您使用ArrayList

List<String> finals = new ArrayList<String>();
...
finals.add(content);

而你的方法可以返回List<String> ,但如果你需要数组,你可以改变它:

String[] array = new String[finals.size()];
finals.toArray(array);

return array;


Answer 4:

EDIT2我几乎猜到- NetworkOnMainThreadException 。 将在不同的线程的代码。 我建议使用AsyncTask

编辑

如果应用程序在try块之前崩溃,那么很可能你已经错过了这个权限添加到您的清单:

<uses-permission android:name="android.permission.INTERNET" /> 

同时,你需要改变这一行

content.substring(content.indexOf("\\u003Cb\\u003E ")+"\\u003Cb\\u003E ".length(), content.indexOf("\\u003C\\/b"));

content = content.substring(content.indexOf("\\u003Cb\\u003E ")+"\\u003Cb\\u003E ".length(), content.indexOf("\\u003C\\/b"));

该方法不影响字符串的当前实例,但返回一个新的。



文章来源: Parsing a JSON file in Android Application