Calc
Calc

Reputation: 535

GSON parsing of nested array

Im having difficulties understanding if GSON can handle this kind of json by default or do I need to implement deserializers for every sub element.

json input

{
   "services":[
      {
         "id": 2,
         "name": "Buy"
      },
      {
         "id": 3,
         "name": "Sell"
      }
      ]
   "status": {
      "code": 0,
      "message": ""
   }
}

The best case result on my part is to have the following class contain all the data

java [ POJO ]

public class Services {
    public List<ServiceItem> services;
    public Status status;

    public class ServiceItem {
        public int id;
        public String name;
    }

    public class Status {
        public int code;
        public String message;
    }
}

Is it possible to let GSON the class and the json and just let it work? Or do I need to create deserializers for each sub class?

Upvotes: 1

Views: 979

Answers (1)

MChaker
MChaker

Reputation: 2649

Correct your json input as follow (you forgot a comma before status field)

{
   "services":[
      {
         "id": 2,
         "name": "Buy"
      },
      {
         "id": 3,
         "name": "Sell"
      }
      ],
   "status": {
      "code": 0,
      "message": ""
   }
}

Then let's consider your classes as follow

public class Services {
    public List<ServiceItem> services;
    public Status status;
    // getters and setters
    @Override
    public String toString() {
        return "["+services.toString()+status.toString()+"]";
    }

    public class ServiceItem {
        public int id;
        public String name;
        // getters and setters
        @Override
        public String toString() {
            return "("+id+","+name+")";
        }

    }

    public class Status {
        public int code;
        public String message;
        // getters and setters
        @Override
        public String toString() {
            return ",("+code+","+message+")";
        }
    }
}

If the input is a file jsonInput.json then

Gson gson = new Gson();
Services data = gson.fromJson(new BufferedReader(new FileReader(
        "jsonInput.json")), new TypeToken<Services>() {
}.getType());
System.out.println(data);

If the input is a json String jsonInput then

Gson gson = new Gson();
Services data = gson.fromJson(jsonInput, Services.class);
System.out.println(data);

Output:

[[(2,Buy), (3,Sell)],(0,)]

Upvotes: 2

Related Questions