Gsonを使ったjsonのパースがうまくいかない
以下のコードを使って以下のjsonから値を取得しようとしています.
{
"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;
int w=0;
int h=0;
Log.d("json",pMosaic);
JsonObject jsonObject=(JsonObject) new Gson().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();
int imgNum[]=new int[w*h];
for (int i=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));
}
}
しかし以下のようなエラーが出ます
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)
at com.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.
どうすれば正しく動きますか?