简体   繁体   English

使用多个主键解析json配置

[英]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.如上所述,我有一个 json 配置数据。

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

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

The pojos is like the one mentioned above. pojos 就像上面提到的那个。 I could easily deserialize the json configuration into a java Map<String, Person> and search using SSN.我可以轻松地将 json 配置反序列化为 java Map<String, Person>并使用 SSN 进行搜索。

Question: How can I deserialize to get two maps - one keyed on SSN and other with driving license?问题:如何反序列化以获取两张地图 - 一张输入 SSN,另一张使用驾驶执照? I could use the SSN->person map to create another map DrivingLicense->Person.我可以使用 SSN->person 地图来创建另一个地图 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按驾照查询不需要 SSN 作为输出
  3. There could be other uniquely identifying keys in the Person class Person 类中可能还有其他唯一标识键

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()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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