Search code examples
jsonrestspring-bootresttemplate

@RequestBody on a Rest method


I have a controller with a lot of methods where I receive a simple property as data, like

-d '{ "email": "rostany.sabater@gmail.com" }'

for all this methods I create a class with a simple property:

@RequestBody MyClass myClass

, and I wonder if there is a simple way to do it instead of creating a lot of classes for a simple property


Solution

  • As suggested in comments you can use a map as its json which is k,v pairs

    or

    to keep it clean and organised why not create a generic class which has a list of in this format [{"key":"k0","value":"v0"},{"key":"k1","value":"v1"}]

    e.g. URI is /baseri?requestVariableLong=[{"key":"k0","value":"v0"},{"key":"k1","value":"v1"}]

    i.e. JSON representation of the List<MyClass> class as shown below

    class MyClass{
        String key;
        String value;
    // constructors 
    //getters
    //setters
    }
    

    In one line of code below you can convert query parameter MyClass in to List

    new Gson().fromJson(requestVariableLong,MyClass.class);
    

    you can iterate over list which will be dynamic and do whatever you want....