Parsing a JSON file in Android Application

2019-09-03 17:35发布

I have a JSON file looking like this:

{
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}}
    ]
    "}/*""*/

I would like to parse the strings like "doomed", "in the heart", "evil" etc. But I am new to both Android and JSON parsing. So please could you please check my progress about parsing this kind of JSON. Here is my function for this:

@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;
    } 

I tried debugging the application but I can't reach into the try block due to some source files missing error that I could not make sense of. As far as I can see, it successfully creates JSONParserobject.

EDIT: 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

4条回答
Anthone
2楼-- · 2019-09-03 17:51

EDIT2 I almost guessed - NetworkOnMainThreadException. Move the code on different thread. I recommend using AsyncTask

EDIT

if the app crashes before the try block, then most probably you have missed to add this permission to your manifest:

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

also, you need to change this line

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

to this

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

the method does not affect the current instance of the string but returns a new one.

查看更多
放荡不羁爱自由
3楼-- · 2019-09-03 17:52

Why not make life simpler for yourself and use Gson? Based on your code I knocked up a quick sample:

Create a POJO to represent your model:

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;

}

Now create an instance from the Json string

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
}
查看更多
Emotional °昔
4楼-- · 2019-09-03 18:06

I think you have problem in that string:

String[] finals = null;

You don't create array of Strings but use it in cycle:

finals[i] = content;

In that case i can reccomend you to use ArrayList:

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

And your method can return List<String>, but if you need Array, you can transform it:

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

return array;
查看更多
不美不萌又怎样
5楼-- · 2019-09-03 18:11

The d:"[ ... ]" is not an JSONArray but a String.

You need to get that string and parse to JSON again.

查看更多
登录 后发表回答