Lina Lina - 1 year ago 120
JSON Question

Converting Json attribute name to entity property name in a Spring MVC GET request

Hi I have an application which is using SpringDataNeo4j , Spring MVC ...
I have the following classes as examples. One is the entity and the other is the JSON object.

public class MyBean() {

@Property(name = "my_name")
String my_name;
@Property(name = "last_modified_by")
String last_modified_by;

//setter & getters


public class MyBeanData {

String myName;
String lastModifiedBy;

//setter getters

This is the request handler in my spring mvc controller :

@RequestMapping(value = "/test", method = RequestMethod.GET)
public List<MyBeanData> getMyBeans(@RequestParam(name = "sortDir", required = false) String sortDir,
@RequestParam(name = "sortProp", required = false) String sortProp){

//execute the Custom query to get all mybeans sorted by sortProp

Now my problem is that the property names used in "sortProp" are the json object attribute names for example "lastModifiedBy"... The sort query does not work with json attribute names it works only if I use entity property names . Is there an easy & clean way to convert a single json attribute NAME to the corresponding entity property NAME before executing the query ?like annotations ?? I do not want to add a converter method like the one below in the entity with so many if elses .

public String converter(String sortProp){
return "last_modified_by"

Answer Source

First of all, you don't need to use many if/elses even if you want to repeatedly compare strings, you can switch on strings:

 switch (sortPro) {
     case "lastModifiedBy": return "last_modified_by";
     // ...

However, the simplest way to store the mapping and do the conversion is to use a Map<String, String>:

private static final Map<String, String> SORT_FIELD_MAP;

static {
    Map<String, String> sortFieldMap = new HashMap<>();
    sortFieldMap.put("lastModifiedBy", "last_modified_by");
    // ...
    SORT_FIELD_MAP = Collections.unmodifiableMap(sortFieldMap);

public String converter(String sortProp) {
    return SORT_FIELD_MAP.get(sortProp);

(Or use immutable collections from Guava or equivalent)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download