将java对象转换成json字符串

0o好好先生o0 / 2024-09-26 / 原文

导入包

import com.fasterxml.jackson.databind.ObjectMapper;

 

/**
* 将java对象转换成json字符串
*
* @param obj
* 准备转换的对象
* @return json字符串
* @throws Exception
*/
public static String beanToJson(Object obj) {
  ObjectMapper objectMapper = new ObjectMapper();
  try {
    String json = objectMapper.writeValueAsString(obj);
    return json;
  } catch (Exception e) {
    throw new Exception(e);
  }
}