简体   繁体   中英

Gson error expected begin_object but was string at line 1 column 1 path $

I hope you could give me a hand on a Gson issue I can't solve. It is quiet common apparently since I found many topic on this subject, but didn't manage to use answers.

I have this error :

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBjECT but was STRING at line 1 column 1 path $

Here is my Json :

{"valeurs":[{"Ident":"1","Lien":"r8WzdMerigo","Categorie":"1"},{"Ident":"2","Lien":"neqgJGz08Fw","Categorie":"2"}],"success":1} 

Then my POJO:

public class gitmodel {


@SerializedName("Ident")
@Expose
private int Ident;

@SerializedName("Lien")
@Expose
private String Lien;

@SerializedName("Categorie")
@Expose
private int Categorie;




public int getIdent() {return Ident;}


public String getLien() {
    return Lien;
}



public int getCategorie() {
    return Categorie;
}

}

And finally in the Main activity :

RestAdapter restAdapter = new RestAdapter.Builder()
                    .setEndpoint(API)
                    .build();

            gitapi git = restAdapter.create(gitapi.class);


            git.getFeed("affichage_bd.php", new Callback<gitmodel>() {
                @Override
                public void success(gitmodel gitmodel, Response response) {
                    tv.setText("Numero categorie :" + gitmodel.getCategorie() + "\nLien :" + gitmodel.getLien() + "\nIdentification :" + gitmodel.getIdent());
                }

                @Override
                public void failure(RetrofitError error) {
                    tv.setText(error.getMessage());
                }
            });
        }
    });

Could you please tell me what's going on?

You are missing a level. The POJO you set in Callback<> should be :

public class MyModel
{
  List<gitmodel> valeurs;

  public List<gitmodel> getValeurs()
   {
     return valeurs;
   }
}

Edit:
You should save the MyModel class somewhere in you project, and then change your interface to:

public interface gitapi {

   @GET("/users/{user}") 
   public void getFeed(@Path("user") String user, Callback<MyModel> myModel); 
}

So then in your MainActivity :

git.getFeed("affichage_bd.php", new Callback<MyModel>() {
                @Override
                public void success(MyModel myModel, Response response) {
                    List<gitmodel> valeurs = myModel.getValeurs();
                    //  here you can iterate through the elements on the list
                }

                @Override
                public void failure(RetrofitError error) {
                    tv.setText(error.getMessage());
                }
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM