本文主要是介绍下划线对象转驼峰,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
场景:
Json的字符串转对象,并且字符串的的属性是下划线,对象的属性是驼峰 ,用在对象中设置属性的方法实现。
方法:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;public class JsonUtils {/*** 下划线转驼峰* @param json* @param clazz* @return* @param <T>* @throws Exception*/public static <T> T underscoreToCamelCaseJson(String json, Class<T> clazz) throws Exception {ObjectMapper mapper = new ObjectMapper();// 先将JSON字符串反序列化为JsonNodeJsonNode rootNode = mapper.readTree(json);// 深度拷贝JsonNode,避免直接修改导致的ConcurrentModificationExceptionObjectNode newNode = mapper.createObjectNode();Map<String, JsonNode> updates = new HashMap<>();// 遍历JSON节点,记录下划线转驼峰后的键值对Iterator<Map.Entry<String, JsonNode>> fields = rootNode.fields();while (fields.hasNext()) {Map.Entry<String, JsonNode> field = fields.next();String oldKey = field.getKey();String newKey = toCamelCase(oldKey);updates.put(newKey, field.getValue());}// 将更新应用于新的JsonNodefor (Map.Entry<String, JsonNode> entry : updates.entrySet()) {newNode.set(entry.getKey(), entry.getValue());}// 现在JSON的键已经是驼峰式命名了,可以直接反序列化为目标类return mapper.treeToValue(newNode, clazz);}}
@GetMapping("/test2")public R test2() throws Exception {String json = "{\n" +" \"reg\": null,\n" +" \"cpn\": null,\n" +" \"name\": null,\n" +" \"sn\": null,\n" +" \"upic\": null,\n" +" \"vin\": null,\n" +" \"fcsn\": null,\n" +" \"operation_type\": null,\n" +" \"imsi\": null,\n" +" \"product_id\": 0,\n" +" \"pilot_id\": 0,\n" +" \"hangar_id\": \"cc\",\n" +" \"hangar_status\": 33\n" +" }";try {DroneDeviceVO myObject = JsonUtils.underscoreToCamelCaseJson(json, DroneDeviceVO.class);log.info(myObject.getHangarId());log.info(""+myObject.getHangarStatus());return R.ok(myObject);} catch (Exception e) {e.printStackTrace();}return R.ok();}
@Datapublic class DroneDeviceVO {private String reg;private String cpn;private String name;private String sn;private String upic;private String vin;private String fcsn;private String operationType;private String imsi;private int productId;private int pilotId;private String hangarId;private int hangarStatus;}
这篇关于下划线对象转驼峰的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!