问题描述:
在项目中使用Long作为表主键,在前后端交互时,由于long类型传递到前端会引起精度问题,所以要求返回给前端的json中long类型数值必须为String,于是提供本方法。参考了使用fastjson转换的案例,链接:fastjson将对象中数值转换为String
代码如下,拷贝即可
public class JSONUtils {
private static final ObjectMapper mapper = new ObjectMapper();
public static Object setNumberValueToString(String json) throws IOException {
if (json instanceof String) {
JsonNode rootNode = mapper.readTree(json);
if (rootNode.isObject()) {
return toObjectNode((ObjectNode) rootNode);
} else if (rootNode.isArray()) {
return toArrayNode((ArrayNode) rootNode);
}
} else {
throw new RuntimeException("json is not String type");
}
return json;
}
private static ObjectNode toObjectNode(ObjectNode node) throws IOException {
ObjectNode newNode = mapper.createObjectNode();
Iterator<Map.Entry<String, JsonNode>> iterator = node.fields();
while (iterator.hasNext()) {
Map.Entry<String, JsonNode> entry = iterator.next();
// 处理 entry
JsonNode valueNode = entry.getValue();
if (valueNode.isNumber()) {
newNode.put(entry.getKey(), valueNode.asText());
} else if (valueNode.isObject()) {
newNode.set(entry.getKey(), toObjectNode((ObjectNode) valueNode));
} else if (valueNode.isArray()) {
newNode.set(entry.getKey(), toArrayNode((ArrayNode) valueNode));
} else {
newNode.set(entry.getKey(), valueNode);
}
}
return newNode;
}
private static ArrayNode toArrayNode(ArrayNode node) throws IOException {
ArrayNode newNode = mapper.createArrayNode();
for (JsonNode element : node) {
if (element.isObject()) {
newNode.add(toObjectNode((ObjectNode) element));
} else if (element.isArray()) {
newNode.add(toArrayNode((ArrayNode) element));
} else {
newNode.add(element);
}
}
return newNode;
}
}