2

I keep getting null when I try to read.

json file

{
  "team": {
   "name": "john 1",
   "id": "12345"
    }
 }

Trying to do it by POJO

public class Team {

    private String name;
    private String id;

    public String getName(){
        return name;
    }
}

My main

public static void main(String[] args) throws IOException {
    Gson gson = new Gson();

    BufferedReader br = new BufferedReader(new 
    FileReader("C:/Users/John/Desktop/back.json"));

    Team test = gson.fromJson(br, Team.class);

    System.out.println(getName());
}

1 Answer 1

2

According to above JSON structure you should have POJO with property team

public class Response {

  private Team team

  //getters and setters
   }

and Team POJO

public class Team {

  private String name;
  private String id;

  // getters and setters
  }

In Main class

Response test = gson.fromJson(br, Response.class);  //from this get Team
Team team = test.getTeam();
Sign up to request clarification or add additional context in comments.

2 Comments

is there anyway to combine Response and Team into one class?
at least can you use nested static class? @jovan, and you can do this into one class by using some external libraries or custom deserializer

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.