4

I am trying to use JSON string, Retrofit and other things in my application. But in this particular model something is making my JSON string to be null.

This is the method where I deserialize my string:

public static class TaskGSON implements JsonSerializer<Task>, JsonDeserializer<Task>{

    @Override
    public Task deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
      System.out.println(json.toString());
      if (!json.isJsonNull()) {
        final JsonObject jsonObject = json.getAsJsonObject();
        Task t = new Task();
        t.mId = jsonObject.get(NAMES.Server.ID).getAsString();
        t.mProjectId = jsonObject.get(NAMES.Server.PROJECT_ID).getAsString();
        t.mTitle = jsonObject.get(NAMES.Server.TITLE).getAsString();
        t.mPriority = Priority.deSerialize(jsonObject.get(NAMES.Server.PRIORITY).getAsString());
        t.mCreatedAt = context.deserialize(jsonObject.get(NAMES.Server.CREATED_AT), Date.class);
        t.mCreatedById = jsonObject.get(NAMES.Server.CREATED_BY_ID).getAsString();
        t.mUpdatedAt = context.deserialize(jsonObject.get(NAMES.Server.UPDATED_AT), Date.class);
        t.mFeedCount = jsonObject.get(NAMES.Server.FEED_COUNT).getAsInt();
        t.mPermissions = context.deserialize(jsonObject.get(NAMES.Server.PERMISSIONS), new TypeToken<List<Permission>>() {}.getType());

        if (jsonObject.has(NAMES.Server.COLLECTION_ID)) {
          t.mCollectionId = jsonObject.get(NAMES.Server.COLLECTION_ID).getAsString();
        }

        if (jsonObject.has(NAMES.Server.DESCRIPTION)) {
          t.mDescription = jsonObject.get(NAMES.Server.DESCRIPTION).getAsString();
        }
        if (jsonObject.has(NAMES.Server.DUE_DATE) && !jsonObject.get(NAMES.Server.DUE_DATE).isJsonNull()) {
          t.mDueDate = context.deserialize(jsonObject.get(NAMES.Server.DUE_DATE), Date.class);
        }

        if (jsonObject.has(NAMES.Server.COMPLETED_AT)) {
          t.mCompletedAt = context.deserialize(jsonObject.get(NAMES.Server.COMPLETED_AT), Date.class);
        }

        if (jsonObject.has(NAMES.Server.COMPLETED_BY_ID)) {
          t.mCompletedById = jsonObject.get(NAMES.Server.COMPLETED_BY_ID).getAsString();
        }

        if (jsonObject.has(NAMES.Server.DELETED_AT)) {
          t.mDeletedAt = context.deserialize(jsonObject.get(NAMES.Server.DELETED_AT), Date.class);
        }

        if (jsonObject.has(NAMES.Server.COMPLETED)) {
          t.mCompleted = jsonObject.get(NAMES.Server.COMPLETED).getAsBoolean();
        }

        if (jsonObject.has(NAMES.Server.CHECKLIST)) {
          t.mChecklists = context.deserialize(jsonObject.get(NAMES.Server.CHECKLIST), new TypeToken<List<Checklist>>() {}.getType());
        }

        if (jsonObject.has(NAMES.Server.ATTACHMENTS)) {
          t.mAttachments = context.deserialize(jsonObject.get(NAMES.Server.ATTACHMENTS), new TypeToken<List<Attachment>>() {}.getType());
        }

        if (jsonObject.has(NAMES.Server.MARKERS)) {
          t.mMarkers = context.deserialize(jsonObject.get(NAMES.Server.MARKERS), new TypeToken<List<Marker>>() {}.getType());
        }
        if (jsonObject.has(NAMES.Server.CATEGORY_ID)) {
         t.mCategory = jsonObject.get(NAMES.Server.CATEGORY_ID).getAsString();
        }

        return t;
      } else {
        return null;
      }
    }

So, the problem is that, when I comment the lines of code that check if there's a field "description" and "categoryId" in my JSON string I don't get the error, but if I uncomment these if statements I get the error saying that the Json is null. And I don't know why.

This is the complete logcat:

09-22 17:02:57.890 21172-26613/com.construct.test E/AbstractEntitiesViewModel: Error java.lang.UnsupportedOperationException: JsonNull
   at com.google.gson.JsonElement.getAsString(JsonElement.java:191)
   at com.construct.v2.models.entities.task.Task$TaskGSON.deserialize(Task.java:740)
   at com.construct.v2.models.entities.task.Task$TaskGSON.deserialize(Task.java:717)
   at com.google.gson.internal.bind.TreeTypeAdapter.read(TreeTypeAdapter.java:69)
   at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
   at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:82)
   at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
   at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
   at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25)
   at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:119)
   at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:218)
   at retrofit2.OkHttpCall.execute(OkHttpCall.java:180)
   at retrofit2.adapter.rxjava.CallExecuteOnSubscribe.call(CallExecuteOnSubscribe.java:40)
   at retrofit2.adapter.rxjava.CallExecuteOnSubscribe.call(CallExecuteOnSubscribe.java:24)
   at retrofit2.adapter.rxjava.BodyOnSubscribe.call(BodyOnSubscribe.java:36)
   at retrofit2.adapter.rxjava.BodyOnSubscribe.call(BodyOnSubscribe.java:28)
   at rx.Observable.unsafeSubscribe(Observable.java:10256)
   at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:48)
   at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:33)
   at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
   at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
   at rx.Observable.unsafeSubscribe(Observable.java:10256)
   at rx.internal.operators.OperatorMerge$MergeSubscriber.onNext(OperatorMerge.java:248)
   at rx.internal.operators.OperatorMerge$MergeSubscriber.onNext(OperatorMerge.java:148)
   at rx.internal.operators.OnSubscribeFromArray$FromArrayProducer.fastPath(OnSubscribeFromArray.java:76)
   at rx.internal.operators.OnSubscribeFromArray$FromArrayProducer.request(OnSubscribeFromArray.java:58)
   at rx.Subscriber.setProducer(Subscriber.java:211)
   at rx.internal.operators.OnSubscribeFromArray.call(OnSubscribeFromArray.java:32)
   at rx.internal.operators.OnSubscribeFromArray.call(OnSubscribeFromArray.java:24)
   at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
   at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
   at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
   at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
   at rx.Observable.unsafeSubscribe(Observable.java:10256)
   at rx.internal.operators.OperatorSubscribeOn$SubscribeOnSubscriber.call(OperatorSubscribeOn.java:100)
   at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
   at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
   at java.util.concurrent.FutureTask.run(FutureTask.java:237)
   at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
   at java.lang.Thread.run(Thread.java:761)

Both fields description and category can be null, but they exist in my Json. It's weird because it works just fine when I comment the lines.

1 Answer 1

9

You should change from yourJsonObject.getAsString() to yourJsonObject.toString()

Sign up to request clarification or add additional context in comments.

8 Comments

Thank you for the reply. Would you mind explaining to me what is the difference?
I change all the fields from this: t.mId = jsonObject.get(NAMES.Server.ID).toString(); to this: t.mId = jsonObject.get(NAMES.Server.ID).getAsString(); But it didn't work.
Maybe be your jsonObject is a JsonNull See stackoverflow.com/a/27763844/3166697
But it isn't because I print the Json right in the beginning to the method and it shows all the data. I print it like this: System.out.println(json.toString());
This is a bad idea. toString() is not for this purpose. It will not fail if the json is malformed and an array or an object is in the place where you expect a string. That will lead to hard to trace bugs. What you should do is check specifically yourJsonObject.isJsonNull() before yourJsonObject.getAsString() and return null.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.