简体   繁体   中英

Mapper: Object to Key-Values

I have a domain object (DO) and Key-Value (KV) objects. How would I map each field of DO to instance of KV?

Example:

class DomainObject {
    String field1 = "value1";
    String field2 = "value2";
}

class KeyValue {
    String key;
    String value;
}

Input is DomainObject, output - two instances of KeyValue (key="field1", value="value1"; key="field2", value="value2").
PS I've used Dozer for mapping field-to-field, but how would I do field-to-KV?

Maybe you could create a reference of KeyValue in DomainObject therefore each KeyValue would be mapped to a item in the DomainObject's fields List. Something simmilar to this:

List<KeyValue> list = new ArrayList<KeyValue>();
list.add(new KeyValue("field1", "value1"));
list.add(new KeyValue("field2", "value2"));    

DomainObject domainObject = new DomainObject(list);     

class DomainObject {
    List<KeyValue> fields;

    public DomainObject(List<KeyValue> keyValueList){
        this.fields=keyValueList;
    }

    public List<KeyValue> getFields() {
        return fields;
    }
}

class KeyValue {
    String key;
    String value;

    public KeyValue(String key, String value) {
        this.key=key;
        this.value=value;
    }
}

Or maybe you could use a hashmap for this kind of task http://tutorialswithexamples.com/java-map-and-hashmap-tutorial-with-examples/

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