jackson转换数据是,json数据中出现int类型数据

如题:
后台使用的是jdbc查询数据库,RS映射是Map<String,Object>,在查询完成之后,直接返回个客户端,spring自动调用jackson转换为json.
现在出现,当数据库数据为int等类型是,返回给前端的数据是int类型或double类型的,
示例:
现在的数据: "test":111
我期望的数据: "test":"111"

能通过配置解决吗?因为项目以及比较庞大了,望大神告知,感谢.

阅读 13.9k
6 个回答

为什么直接把数据库查询出来的对象转成json,中间加一层DTO转换一下吧,想偷懒用这个注解:

@JsonSerialize(using = ToStringSerializer.class)
private Long id;

遍历jdbc查出来的结果集拿出来转成string可不可行

jackson把对象转成json格式就已经是你要求的格式了,试着打印出来看看

谢邀,现在少用的 Java,所以这些东西不熟了。

处理办法有两类,一类是你自己把类型转换成 String,这样生成的 JSON 肯定是带引号的,但是这样需要修改模型或者添加适配模型

另一类方法是从 jackson 的文档中去找能否自定义 Converter,或者做类型映射,它的文档中找到下面这样一段,看样子至少是可以定义 Converter 的,还可以尝试一下 as 或者 contentAs。不过具体怎么做……我没找到 javadoc,所以不太清楚,没时间去试验研究。

Serialization (writing JSON)

  • @JsonSerialize (method, field) can be used to denote:

    • Explicit serializer (of type JsonSerializer) to use, with following properties:

      • using for value of property itself
      • keyUsing for keys of java.util.Map valued properties
      • contentUsing for contents of structured values (elements of arrays, java.util.Collections, values of java.util.Maps)
      • nullUsing when serializing Java null valued properties (NEW with 2.3)
    • Explicit type to use (instead of actual run time type) with

      • as for property value
      • keyAs for java.util.Map keys
      • contentAs for elements/values of structured types
      • NOTE: type used must be compatible with nominal type (a super type)
    • Whether static or dynamic typing (default: static typing) is to be used: typing property

      • Allowed values are DYNAMIC (for dynamic runtime type), STATIC (to use declared, "nominal" type) or DEFAULT_TYPING to use defaults for ObjectMapper
    • Converter object (of type Converter) to use

      • converter for property value itself, or
      • contentConverter for values of structured types (elements of array, java.util.Collections; values of java.util.Maps)
json = json.replace("\":\"", "\":");
json = json.replace("\",", ",");
json = json.replace("\":", "\":\"");
json = json.replace(",", "\",");
强行改行不行-。-

方法一:如楼上所说,使用@JsonSerialize注解,方法二:增加dto使用BeanUtilsBean工具类转换

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题