简体   繁体   中英

Parsing json configuration with multiple primary keys

{
    "ssn1": {
        "name": "person1",
        "address": "address1"
        "drivingLicense": "dl1"
    },
    "ssn2": {
        "name": "person2",
        "address": "address2"
        "drivingLicense": "dl2"
    }
}

I have a json configuration data as mentioned above.

class Citizen {
    Map<String, Person> personMap;
}

class Person {
    String name;
    String address;
    String drivingLicense;
}

The pojos is like the one mentioned above. I could easily deserialize the json configuration into a java Map<String, Person> and search using SSN.

Question: How can I deserialize to get two maps - one keyed on SSN and other with driving license? I could use the SSN->person map to create another map DrivingLicense->Person. Can I create the DrivingLicense map in an elegant way to that I don't have to write

ssnMap.entrySet().stream().collect(Collectors.toMap(
            e -> e.getValue().getDrivingLicense(),
            e -> e.getValue()));

again and again for other primary keys like passport number?

Assumptions

  1. Driving license is unique for each person
  2. Query by driving license does not require SSN as output
  3. There could be other uniquely identifying keys in the Person class

You can't do that with any kind of content-agnostic deserialization, which operates only on structure. You can do something trivial in postprocessing like

var byDl = bySsn.values().stream().collect(toMap(Person::drivingLicense, identity()));

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