1

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?

1
  • that is not valid json Commented May 17, 2015 at 9:44

1 Answer 1

2

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,)]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.