简体   繁体   中英

Parsing two JSON files to POJOS, one references the other

I have two files: occupations.json and people.json . The former is just an array of occupations:

[
    { "name": "director", "pay": "100000"},
    { "name": "programmer", "pay": "75000"},
    { "name": "teacher", "pay": "50000"}
]

And the latter an array of a few people along with their occupation:

[
    { "name": "Mary", "occupation": "programmer" },
    { "name": "Jane", "occupation": "director" },
    { "name": "John", "occupation": "teacher" }
]

And these are the corresponding classes:

public class Occupation {
    private final String name;
    private final int pay;


    public String getName() { ... }
    public int getPay() { ... }
}

public class Person {
    private final String name;
    private final Occupation occupation;

    public String getName() { ... }
    public String getOccupation() { ... }
}

Currently I'm using ObjectMapper.readValue(InputStream, Class) to unserialize the files. How can I make Person class aware of all existing Occupation objects? I want to select which occupation a person has by using the occupation's name.

add a function to Person.class

public Occupation getOccupation_()
{
  // assume you had a static occupations list...
  for (Occupation o : occupations)
    if (o.name == this.occupation)
      return o;

  return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM