将<key,value>对象的java.util.Set转换为简单的pojo对象

时间:2018-07-04 23:29:28

标签: java collections set mapping

获取仅具有键值对作为输入的java.util.Set对象,如下所示

public class KeyValueObject {
String key;
String value;

// good old constructor, setters and getters

}

输入对象:     java.util.Set inputObject;

KeyValuePair pair1 = new KeyValuePair("Name":"John");
KeyValuePair pair2 = new KeyValuePair("Age":"28");
KeyValuePair pair3 = new KeyValuePair("Location":"Cincinnati");

inputObject.add(pair1);
inputObject.add(pair2);
inputObject.add(pair3);

以“ inputObject”作为请求进入时,如何将其转换为一个简单的POJO对象,该对象具有上述所有键作为单个参数,如下所示:

Public class SimplePojoObject {
    private String name;
    private String age;
    private String location;

  // Good old setters and getters

}

传入的对象大约有52个对象,这就是为什么手动映射方式不是解决此问题的正确方法的原因。请建议以任何可能的方式映射此数据

2 个答案:

答案 0 :(得分:1)

您可以这样做:

  • Set<KeyValueObject>转换为JsonNode(或Map<String, String>)对象。
  • 使用JsonNode将生成的Map<String, String>(或SimplePojoObject)对象转换为ObjectMapper(也可以使用Gson库代替ObjectMapper)

如果您已经有一个Map<String, String>对象而不是Set<KeyValueObject>,则只需一行即可:

SimplePojoObject simplePojoObject = new ObjectMapper().convertValue(map, SimplePojoObject.class);

答案 1 :(得分:1)

最简单的方法是编写一个小的方法来调用设置器:

public SimplePojoObject buildSimplePojoObject(Set<KeyValuePair> properties) {
    SimplePojoObject result = new SimplePojoObject();
    for (KeyValuePair prop : properties) {
        switch (prop.getKey()) {
            case "Name":
                result.setName(prop.getValue());
                break;
            case "Age":
                result.setAge(prop.getValue());
                break;
            case "Location":
                result.setLocation(prop.getValue());
                break;
            default:
                // Throw an exception or ignore it.
                throw new IllegalArgumentException("Unknown property "+ prop.getKey());
        }
    }
    return result;
}

但是,如果您想动态地执行此操作,则可以:

public SimplePojoObject buildSimplePojoObject(Set<KeyValuePair> properties) {
    SimplePojoObject result = new SimplePojoObject();
    Lookup l = MethodHandles.publicLookup();
    MethodType mt = MethodType.methodType(void.class, String.class);
    for (KeyValuePair prop : properties) {
        MethodHandle mh = l.findVirtual(SimplePojoObject.class, "set" + prop.getKey());
        try {
            mh.invokeExact(result, prop.getValue());
        } catch (Error | RuntimeException e) {
            throw e;
        } catch (Throwable t) {
            // MethodHandle.invokeExact is declared to throw Throwable, so we have to catch it.
            throw new RuntimeException(e);
        }
    }
    return result;
}