1

I have a Json array like this

String carJson = "[{ \"brand\" : \"Mercedes\", \"doors\" : 5 }, { \"brand\" : \"Mercedes\", \"doors\" : 5 }]";

so far i have done this

Car cars = gson.fromJson(carJson,Car[].class);

and my car class is

  private static class Car {
            private String brand = null;
            private int doors = 0;

            public String getBrand() { return this.brand; }
            public void   setBrand(String brand){ this.brand = brand;}

            public int  getDoors() { return this.doors; }
            public void setDoors (int doors) { this.doors = doors; }
    }

But its not working. How can I convert this string array to Java array? And how to retrieve the elements using the keys?

cнŝdk
  • 31,391
  • 7
  • 56
  • 78

2 Answers2

0

First of all your source Json is incorrect.

The internal arrays should be changed to objects, because arrays aren't a key and value structure, and because these internal objects should be mapped to Car objects.

So change your json string like this:

String carJson = "[{ \"brand\" : \"Mercedes\", \"doors\" : 5 }, { \"brand\" : \"Mercedes\", \"doors\" : 5 }]";

Then these internal objects will be mapped to Car objects in Java, using this code:

Car[] cars = gson.fromJson(carJson, Car[].class);

Then to read the cars array data, you can use:

for(int i=0; i<cars.length; i++){
    Car c = cars[i];
    System.out.println("Car "+ i +" is : Brand= "+ c.getBrand() + "and doors = "+c.getDoors());
}

And this is how should be your Car class defined:

public class Car {
    private String brand;
    private int doors;

    //Constructors

    public String getBrand(){
       return this.brand;
    }

    public void setBrand(String b){
       this.brand = b;
    }

    public String getDoors(){
       return this.doors;
    }

    public void setDoors(int n){
       this.doors= n;
    }
}
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
0

Fix your json:

String carJson ="[{ \"brand\" : \"Mercedes\", \"doors\" : 5 }, { \"brand\" : \"Mercedes\", \"doors\" : 5 }]";

And then you can do:

Car cars[] = new Gson().fromJson(carJson, Car[].class);

class Car {
    private String brand;
    private int doors;
}
Nikolai
  • 760
  • 4
  • 9
  • thanks for your reply. But I m getting an error in "Car cars[] = new Gson().fromJson(carJson, Car[].class);" it says cast..car to class – Bidipta Dauka Feb 20 '18 at 08:20