Kadaj
Kadaj

Reputation: 705

Converting JSON string to array of objects using Gson

I'm having issue with conversion of JSON string into array of objects using Gson. I have tried everything I could have find and nothing helped. My code is:

   public static ProizvodiViewModel GetProizvode(String tip) {
    String strJson = HttpManager.simpleResponseGet("http://192.168.0.15:21951/api/Proizvodi/SearchProizvodiByVrsta", tip);

    Gson gson = new Gson();
    ProizvodiViewModel x = new ProizvodiViewModel();
    x.Proizvodi = new ProizvodViewModel[]{};//tried also with this line commented

    try {
        //1st attempt
        //x.Proizvodi = gson.fromJson(strJson, ProizvodViewModel[].class);

        //2nd
        //Type type = new TypeToken<List<ProizvodViewModel[]>>() {}.getType();
        //x.Proizvodi = gson.fromJson(strJson, type);

        //3rd and so forth (cause many of answers here on SO had almost same idea)
        Type collectionType = new TypeToken<Collection<ProizvodViewModel>>() {}.getType();
        Collection<ProizvodViewModel> enums = gson.fromJson(strJson, collectionType);            
    } catch (Exception e) {
        System.out.println("ERROR IN GSON");
        System.out.println(e.getMessage());
    }
    return x;
}

I had put try catch cause app would break otherwise, and I couldnt read println's.

And my classes:

public class ProizvodViewModel {
   public int Id ;      
   public boolean IsDeleted ;       
   public String Naziv ;
   public float Cijena ;
   public byte[] Slika ;       
   public byte[] SlikaThumb ;       
   public String Status ;
   public int ProizvodDetaljiId ;       
   public int VrstaId ;
}

public class ProizvodiViewModel
{
 public ProizvodViewModel[] Proizvodi;
}

I get data in JSON ,as you can see here: http://pastebin.com/6C7936Uq I am using Android Studio 1.1.0, and api 16.

Edit: Post solved problem. I had my api return json string containing 2 properties of byte arrays, which were converted (I don't know how) into base64 string and I was trying to map them into byte array ,which was causing error. I wrote my api in asp. net application, so if anyone cares to further explain why this happened, please do.

Upvotes: 2

Views: 3289

Answers (1)

Amg91
Amg91

Reputation: 165

I would use ProizvodViewModel without the array. As follows:

public class ProizvodViewModel {
   public int Id ;      
   public boolean IsDeleted ;       
   public String Naziv ;
   public float Cijena ;
   public byte[] Slika ;       
   public byte[] SlikaThumb ;       
   public String Status ;
   public int ProizvodDetaljiId ;       
   public int VrstaId ;
}

then, create a List of ProizvodViewModel, like this:

List<ProizvodViewModel> list = gson.fromJson(strJson, new TypeToken<List<ProizvodViewModel>>(){}.getType());

Also, if specifically you need a array, you could:

ProizvodViewModel[] array = new ProizvodViewModel[list.size()];
list.toArray(array);

Upvotes: 1

Related Questions