Search code examples
javajsonpojovert.x

Maintain parent class reference when converting json to POJOs


I'm using vertx's Json.Decode() to convert a json string into nested Java objects (POJOs). Something like below:

{ "countries" : [ {"name":"country01", "cities":[{"name":"city1"}, {"name":"city2"} ] } ] }

And the target objects are:

Request {
  private List<Country> countries;
  
  public List<Country> getCountries()
  {
    return countries;
  }
  
  public void setCountries(List<Country> cts)
  {
    countries = cts;
  } 
}

Country {
  private String name;
  
  public String getName()
  {
    return name;
  }
  
  public void setName(String n)
  {
    name = n;
  }
  
  private List<City> cities;
  
  public List<City> getCities()
  {
    return cities;
  }
  
  public void setCities(List<City> cts)
  {
    cities = cts;
  } 
}

City {
  private String name;
  ...
}

Now, I would want to be able to have a Countryproperty inside a City object so that I can get the country name of a city. How should I do this?

Thanks a lot!


Solution

  • Use a two step process to reestablish the up links from city to country.

    1. Create the list of pojos (like you are currently doing it).
    2. Post creation, run the list of children and set the parent reference.