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?

3
  • 2
    Make Employee have a single Map<String, Object> props rather than "100+ fields" Commented Mar 21, 2023 at 19:25
  • Does this answer your question? Parse a URI String into Name-Value Collection Commented Mar 21, 2023 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... Commented Mar 21, 2023 at 19:33

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.