使用Jackson将带有下划线的JSON反序列化为Java中的驼峰案例?

时间:2016-08-07 00:55:39

标签: java json jackson

要将具有camel case属性的java对象序列化为带有下划线的json,我们使用PropertyNamingStrategy作为SNAKE_CASE

那么,是否还有相反的事情要做。也就是说,使用下划线将json反序列化为带有驼峰的Java对象。

例如, JSON:

{
    "user_id": "213sdadl"
    "channel_id": "asd213l"
}
应该将

反序列化为此Java对象:

public class User {
    String userId; // should have value "213sdadl"
    String channelId; // should have value "asd213l"
}

我知道one way of doing this是通过@JsonProperty注释,它在字段级别工作。我有兴趣知道任何全球背景。

1 个答案:

答案 0 :(得分:5)

你可以拥有PropertyNamingStrategy的实现,如下所示:

import org.codehaus.jackson.map.MapperConfig;
import org.codehaus.jackson.map.PropertyNamingStrategy;
import org.codehaus.jackson.map.introspect.AnnotatedField;
import org.codehaus.jackson.map.introspect.AnnotatedMethod;

public class CustomNameStrategy extends PropertyNamingStrategy
 {
  @Override
  public String nameForField(MapperConfig
                       config,
   AnnotatedField field, String defaultName) {
     return convert(defaultName);

  }
  @Override
  public String nameForGetterMethod(MapperConfig
                       config,
   AnnotatedMethod method, String defaultName) {
     return convert(defaultName);
  }

  @Override
  public String nameForSetterMethod(MapperConfig
                       config,
    AnnotatedMethod method, String defaultName) {
   String a = convert(defaultName); 
   return a;
  }

  public String convert(String defaultName )
  {
   char[] arr = defaultName.toCharArray();
   StringBuilder nameToReturn = new StringBuilder();

   for(int i=0; i< arr.length(); i++){
      if(arr[i] == '_'){
        nameToReturn.append(Character.toUpperCase(arr[i+1]));
        i++;
      }else{
        nameToReturn.append(arr[i]);
      }
   }
   return nameToReturn.toString();
  }

 }

然后在您的实现或执行desrialization的类中,您可以:

ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(new CustomNameStrategy());
YourClass yourClass = mapper.readValue(yourJsonString, YourClass.class);