Geoff
Geoff

Reputation: 6629

GSON parsing a JSON string

Am trying to parse json string from php via gson in android but keep on getting an error

in php script i have

return json_encode(["valid"=>true,"token"=>$tokenUser->token]);

IN my android on response method i have

void onApiResponse(String response){
 Log.i("test", response) //gives "{\"valid\":false,\"token\":null}"

 //using gson below
VerificationResponse verificationResponse = new Gson().fromJson(response,VerificationResponse.class);

}

And my verification response class has

    private class VerificationResponse{
    private Boolean valid;
    private String token;

    public Boolean getValid() {
        return valid;
    }

    public String getToken() {
        return token;
    }
}

Whenever i try accessing the isValid getter via verificationResponse.getValid() am getting an error

 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
  Expected BEGIN_OBJECT but was STRING

What am i missing in this?

Upvotes: 0

Views: 179

Answers (2)

Pinal Gangani
Pinal Gangani

Reputation: 59

String Json_Header = "Content-Type: application/json;charset=UTF-8";
String Query_Header = "Content-Type: application/x-www-form-urlencoded";

ApiInterface

@POST("Get_Watch_List")
@Headers({Query_Header})
Call<String> GetWatchList(@Query("Token") String Token);

Call Service

  ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
        Call<String> call = apiService.GetWatchList(GlobalApp.Token);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                try {
                    Gson gson = new Gson();
                    VerificationResponse verificationResponse = gson.fromJson(response.body(), VerificationResponse.class);
                    if (verificationResponse.getValid().equals("true")) {
                        // here your code
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });

Upvotes: 1

Martin Marconcini
Martin Marconcini

Reputation: 27226

To Serialize an object TO Json (not FROM Json) and to verify if your model/json are working together, it's very easy to try to see how an object is first serialized and compare that.

So (in Kotlin because it's shorter):

import android.util.Log
import com.google.gson.Gson

data class Thing(val value: Boolean, val token: String)

class SerializeMyThing {
    init {
        val thing = Thing(true, "token2")
        val gson = Gson()
        val thingAsJsonString = gson.toJson(thing, Thing::class.java)

        Log.d("THING", thingAsJsonString)

    }
}

Thing is my model, it takes a value (Boolean) and a String called token, like yours.

Then I simply created a Gson instance and called toJson...

This is the output of the above:

D/THING: {"token":"token2","value":true}

If you wanted to go BACK to an object (which is what you're trying to do), add this after the first log to verify it's working:

        // back to Object from the thingAsJson:
        val newThing = gson.fromJson(thingAsJsonString, Thing::class.java)
        Log.d("THING", "Value: " + newThing.value + " | token: " + newThing.token)

Prints (as expected):

D/THING: Value: true | token: token2

What I think you're having issues with is the format of your Json gotten from the server:

It looks like this according to your question:

"{\"valid\":false,\"token\":null}"

Where I think it should be more like:

{"valid":false,"token":null}

Upvotes: 0

Related Questions