【问题标题】:map JSON string to entity without nested entity将 JSON 字符串映射到没有嵌套实体的实体
【发布时间】:2013-02-19 18:34:13
【问题描述】:

我正在使用 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 字符串

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

【问题讨论】:

  • 我认为实现这一点的唯一方法是从请求中获取原始字符串 JSON 值并手动转换。根据您使用的 JSON 库(Jackson、FlexJSON),它应该提供一种将 JSON 值自定义映射到相应对象值的方法。

标签: java json spring-mvc


【解决方案1】:

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

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

但无论如何都需要转换。

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 2013-10-02
    • 1970-01-01
    • 2016-06-07
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    相关资源
    最近更新 更多