2

I have a json request which hits a post mapping call

{   "xyz":"tyu",

    "abc":"test1=1&test2=2&.....test100=100"
}

There are 100+ key value pairs in the field abc. How do I map it to a java class which contains these 100+ fields

My approach:

@PostMapping("/employee")
    public Response someMethod(@RequestBody Employee emp) {
           
        String reqStream = emp.getAbc();
        String[] reqStreamArray = reqStream.split("&");

        for (String pair : reqStreamArray) {
            String[] reqStreamKeyValue = pair.split("=");
            String key = reqStreamKeyValue[0];
            String value = reqStreamKeyValue[1];
            switch (key) {
                case "test1":
                    emp.setTest1(value);
                    break;

So the problem is I need to have 100+ switch stmts which is wrong. What is the better approach?

Coder17
  • 767
  • 4
  • 11
  • 30
  • 2
    Make `Employee` have a single `Map props` rather than "100+ fields" – OneCricketeer Mar 21 '23 at 19:25
  • Does this answer your question? [Parse a URI String into Name-Value Collection](https://stackoverflow.com/questions/13592236/parse-a-uri-string-into-name-value-collection) – xerx593 Mar 21 '23 at 19:26
  • 2
    It's "url specific", but quite popular... top answer can be refactored to strings (with/-out decoding) + many (good) "string based" answers... – xerx593 Mar 21 '23 at 19:33

1 Answers1

1

Assuming the normal getter/setter pairs are on the target class, recommend such as the Apache commons-beanutils library for simplicity:

BeanUtils.setProperty(emp, key, value);

To achieve the same without an external library, java.beans.Introspector will return an array of PropertyDescriptor for a class. These would need sifting by name, for example:

PropertyDescriptor[] propertyDescriptors = Introspector
    .getBeanInfo(Employee.class).getPropertyDescriptors();
PropertyDescriptor propertyDescriptor = Arrays
    .stream(propertyDescriptors)
    .filter(p -> p.getName().equals(key)).findAny()
    .orElseThrow(() -> new IllegalArgumentException(
        String.format("Property not found: %s", key)));
propertyDescriptor.getWriteMethod().invoke(emp, value);
df778899
  • 10,703
  • 1
  • 24
  • 36