JSON 驼峰转下划线

来源:互联网 发布:商之翼 yii2.0 源码 编辑:程序博客网 时间:2024/04/30 12:32
import com.fasterxml.jackson.databind.PropertyNamingStrategy.PropertyNamingStrategyBase;public class MyCamemlToUnderlineCaseStrategy extends PropertyNamingStrategyBase {private static final long serialVersionUID = 1L;@Overridepublic String translate(String input) {if (input == null)return input; // garbage in, garbage outint length = input.length();StringBuilder result = new StringBuilder(length * 2);int resultLength = 0;boolean wasPrevTranslated = false;for (int i = 0; i < length; i++) {char c = input.charAt(i);if (i > 0 || c != '_') // skip first starting underscore{if (c == '_') {if (!wasPrevTranslated && resultLength > 0 && !Character.isUpperCase(result.charAt(resultLength - 1))) {if (++i < length) {result.append(Character.toUpperCase(input.charAt(i)));resultLength++;}}wasPrevTranslated = true;} else {wasPrevTranslated = false;result.append(c);resultLength++;}}}return resultLength > 0 ? result.toString() : input;}}



import java.io.IOException;import java.io.Serializable;import com.fasterxml.jackson.core.JsonParseException;import com.fasterxml.jackson.databind.JsonMappingException;import com.fasterxml.jackson.databind.ObjectMapper;public class JacksonTest {public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {ObjectMapper mapper = new ObjectMapper();String json = "{\"userName\":\"bflee\",\"idNumber\":\"123456\"}";mapper.setPropertyNamingStrategy(new MyCamemlToUnderlineCaseStrategy());O o = (O) mapper.readValue(json, O.class);System.out.println(o.getId_number());}}class O implements Serializable {private static final longserialVersionUID= -3004824622398622080L;private Stringuser_name;private Stringid_number;public String getUser_name() {return user_name;}public void setUser_name(String user_name) {this.user_name = user_name;}public String getId_number() {return id_number;}public void setId_number(String id_number) {this.id_number = id_number;}}


0 0
原创粉丝点击