Perth of json using Gson doesn't work

Asked 2 years ago, Updated 2 years ago, 100 views

I'm trying to get a value from the following json using the code below.

{
"block_size": 50,
"mosaic_size_h"—45,
"mosaic_size_w"—80,
"0":"0",
"1":"3",
"2":"3",
"3":"3",
"4":"3",
...
}
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.Arrays;

public class CreateMosaic {
    public void CreateMosaicArt (String pMosaic) {
        int size = 0;
        intw = 0;
        inth = 0;
        Log.d("json", pMosaic);

        JsonObject jsonObject=(JsonObject)newGson().fromJson(pMosaic, JsonObject.class);

        size = jsonObject.getAsJsonObject().get("block_size").getAsInt();
        w=jsonObject.getAsJsonObject().get("mosaic_size_w").getAsInt();
        h=jsonObject.getAsJsonObject().get("mosaic_size_h").getAsInt();
        intimgNum[] = new int[w*h];
        for(inti=2;i<jsonObject.size();i++){
            imgNum[i] = jsonObject.getAsJsonObject().get(String.valueOf(i)) .getAsInt();
        }
        Log.d("size", String.valueOf(size));
        Log.d("w", String.valueOf(w));
        Log.d("h", String.valueOf(h));
        Log.d("imgs", Arrays.toString(imgNum)));

    }

}

However, I get the following error

E/AndroidRuntime:FATAL EXCEPTION:main
    Process: com.example.tadatouta.downloadtest, PID: 14807
    java.lang.NullPointerException: Attempt to Invoke virtual method 'int com.google.gson.JsonElement.getAsInt()' on a null object reference
        at com.example.tadatouta.downloadtest.CreateMosaic.CreateMosaicArt (CreateMosaic.java:30)
        at com.example.tadatouta.downloadtest.MainActivity$1.CallBack(MainActivity.java:25)
        atcom.example.tadatouta.downloadtest.DownloadTask.onPostExecute (DownloadTask.java:93)
        at com.example.tadatouta.downloadtest.DownloadTask.onPostExecute (DownloadTask.java:13)
        at android.os.AsyncTask.finish (AsyncTask.java:695)
        at android.os.AsyncTask. -wrap1 (Unknown Source:0)
        at android.os.AsyncTask$InternalHandler.handleMessage (AsyncTask.java:712)
        at android.os.Handler.dispatchMessage (Handler.java:106)
        at android.os.Looper.loop (Looper.java:164)
        at android.app.ActivityThread.main (ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke (Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:807)
Application terminated.

How can I move correctly?

java json

2022-09-29 21:57

1 Answers

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.