0

我正在使用 Spring MVC 3,我需要将 JSON 字符串映射到实体中。Json 字符串只包含嵌套实体的键引用:

我收到一个 JSON 字符串,如:

{"entities":
    [{
    "entityName":"User",
    "values":
    [
    {"name":"Mario","lastname":"Rossi","id_type":"1"},
    {"name":"Giuseppe","lastname":"Verdi","id_type":"1"}
    ]
    }]
}

我有 2 个 java 实体:

User{
   String name,
   String lastname,
   UserType userType
}

UserType {
   int id,
   String description
}

我想使用 JSON 信息创建我的用户实体。用户类没有“id_type”参数,因此 ObjectMapper 无法将 JSON 字符串放入用户实体中。

我可以接收不同类型的实体,所以我以这种方式使用反射:

//READ JSON
GenericEntity entities[]=request.getEntities();
String entityName = entities[0].getEntityName();
Object rows[] = entities[0].getValues();
//MAP
Class clazz  = Class.forName(entityName);
ObjectMapper mapper = new ObjectMapper();
dbEntity = mapper.convertValue(rows[0], clazz);
//SAVE TO DB
service.save(dbEntity);

我想我必须使用 CustomObjectMapper 但我不知道如何

我也有相反的问题:我得到用户类的“用户”,我必须用“id_type”创建 JSON 字符串

有人可以帮助我吗?提前致谢

4

1 回答 1

0

您可以尝试使用 DTO 对象。例如:

@RequestMapping(value={"/v1/foos"}, method = RequestMethod.POST, consumes="application/json")
public void createFoo(@RequestBody FooDTO requestDTO) throws Exception {
    ...
}

但无论如何都需要转换。

于 2013-02-20T17:44:33.757 回答