0

I have the following JSON , which i need to convert to Java Object

[{
 "emp": {
 "name": "pavan"
 },
 "dept": {
 "deptName": "cse"
 }
}]

I am trying to convert this JSON to Java Object using GSON Framework

public class Root {
 
 private Data data ;
 public Data getData() {
 return data;
 }
 public void setData(Data data) {
 this.data = data;
 }
}
public class Data {
 
 private Emp emp;
 private Dept dept;
 public void setEmp(Emp emp){
 this.emp = emp;
 }
 public Emp getEmp(){
 return this.emp;
 }
 public void setDept(Dept dept){
 this.dept = dept;
 }
 public Dept getDept(){
 return this.dept;
 }
}
public class Emp
{
 private String name;
 public void setName(String name){
 this.name = name;
 }
 public String getName(){
 return this.name;
 }
}
 public class Dept
{
 private String deptName;
 public void setDeptName(String deptName){
 this.deptName = deptName;
 }
 public String getDeptName(){
 return this.deptName;
 }

This is my Test class

public class Test {
 public static void main(String[] args) {
 // TODO Auto-generated method stub
 
 String json = "[{\r\n" + 
 " \"emp\": {\r\n" + 
 " \"name\": \"pavan\"\r\n" + 
 " },\r\n" + 
 " \"dept\": {\r\n" + 
 " \"deptName\": \"cse\"\r\n" + 
 " }\r\n" + 
 "}]";
 
 Gson gson = new Gson();
 
 Root[] root = gson.fromJson(json, Root[].class);
 
 System.out.println(root[0].getData());
 
 }

I am using GSON to convert json to Java Object I am getting null when i do the getData , can anybody please tell me why the conversion is not happening

Bijin Abraham
2,3473 gold badges14 silver badges27 bronze badges
asked Aug 6, 2020 at 15:32
2
  • The emp field needs to be of a type which has a name field (of type String) and the dept field needs to be of a type which has a deptName field also od String. (in this simplistic setting with no annotation etc.) Commented Aug 6, 2020 at 15:37
  • 1
    there's also no data field, so you might need to do Data[] root = gson.fromJson(json, Data[].class); Commented Aug 6, 2020 at 15:45

1 Answer 1

1

The Root class is redundant.

Change

 Root[] root = gson.fromJson(json, Root[].class);

to

 Data[] data= gson.fromJson(json, Data[].class);
answered Aug 6, 2020 at 17:54
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.