使用Jackson自定义JSON格式

20jt8wwn  于 7个月前  发布在  其他
关注(0)|答案(6)|浏览(81)

我用的是Flickr API当调用flickr.test.login方法时,默认的JSON结果是:

{
    "user": {
        "id": "21207597@N07",
        "username": {
            "_content": "jamalfanaian"
        }
    },
    "stat": "ok"
}

我想把这个响应解析成一个Java对象:

public class FlickrAccount {
    private String id;
    private String username;
    // ... getter & setter ...
}

JSON属性应该像这样Map:

"user" -> "id" ==> FlickrAccount.id
"user" -> "username" -> "_content" ==> FlickrAccount.username

不幸的是,我无法找到一个漂亮的,优雅的方式来做这件事使用注解。到目前为止,我的方法是将JSON字符串读入Map<String, Object>并从中获取值。

Map<String, Object> value = new ObjectMapper().readValue(response.getStream(),
        new TypeReference<HashMap<String, Object>>() {
        });
@SuppressWarnings( "unchecked" )
Map<String, Object> user = (Map<String, Object>) value.get("user");
String id = (String) user.get("id");
@SuppressWarnings( "unchecked" )
String username = (String) ((Map<String, Object>) user.get("username")).get("_content");
FlickrAccount account = new FlickrAccount();
account.setId(id);
account.setUsername(username);

但我认为,这是最不优雅的方式,永远。有没有简单的方法,使用注解或自定义的编译器?
这对我来说是非常明显的,但当然它不起作用:

public class FlickrAccount {
    @JsonProperty( "user.id" ) private String id;
    @JsonProperty( "user.username._content" ) private String username;
    // ... getter and setter ...
}
quhf5bfb

quhf5bfb1#

你可以为这个类编写自定义的编译器。它可以看起来像这样:

class FlickrAccountJsonDeserializer extends JsonDeserializer<FlickrAccount> {

    @Override
    public FlickrAccount deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        Root root = jp.readValueAs(Root.class);

        FlickrAccount account = new FlickrAccount();
        if (root != null && root.user != null) {
            account.setId(root.user.id);
            if (root.user.username != null) {
                account.setUsername(root.user.username.content);
            }
        }

        return account;
    }

    private static class Root {

        public User user;
        public String stat;
    }

    private static class User {

        public String id;
        public UserName username;
    }

    private static class UserName {

        @JsonProperty("_content")
        public String content;
    }
}

之后,你必须为你的类定义一个转换器。您可以按如下方式执行此操作:

@JsonDeserialize(using = FlickrAccountJsonDeserializer.class)
class FlickrAccount {
    ...
}
dfddblmv

dfddblmv2#

因为我不想实现一个自定义类(Username)来Map用户名,所以我使用了一种更优雅但仍然很难看的方法:

ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(in);
JsonNode user = node.get("user");
FlickrAccount account = new FlickrAccount();
account.setId(user.get("id").asText());
account.setUsername(user.get("username").get("_content").asText());

它仍然没有我希望的那么优雅,但至少我摆脱了所有丑陋的铸造。这个解决方案的另一个优点是,我的域类(FlickrAccount)没有被任何Jackson注解污染。
根据@ MichaelZiober的回答,我决定使用-在我看来-最直接的解决方案。使用@JsonDeserialize注解和自定义的解析器:

@JsonDeserialize( using = FlickrAccountDeserializer.class )
public class FlickrAccount {
    ...
}

但是,解析器不使用任何内部类,只使用上面的JsonNode

class FlickrAccountDeserializer extends JsonDeserializer<FlickrAccount> {
    @Override
    public FlickrAccount deserialize(JsonParser jp, DeserializationContext ctxt) throws 
            IOException, JsonProcessingException {
        FlickrAccount account = new FlickrAccount();
        JsonNode node = jp.readValueAsTree();
        JsonNode user = node.get("user");
        account.setId(user.get("id").asText());
        account.setUsername(user.get("username").get("_content").asText());
        return account;
    }
}
mi7gmzs6

mi7gmzs63#

您也可以使用SimpleModule。

SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier() {
    @Override public JsonDeserializer<?> modifyDeserializer(
        DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
        if (beanDesc.getBeanClass() == YourClass.class) {
            return new YourClassDeserializer(deserializer);
        }

        return deserializer;
    }});

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(module);
    objectMapper.readValue(json, classType);
zbsbpyhn

zbsbpyhn4#

我是这样做的:

public class FlickrAccount {
  private String id;
  @JsonDeserialize(converter = ContentConverter.class)
  private String username;
  
  private static class ContentConverter extends StdConverter<Map<String, String>, String> {
    @Override
    public String convert(Map<String, String> content) {
      return content.get("_content"));
    }
  }
}
sbdsn5lh

sbdsn5lh5#

Sharing a code snippet for implementing custom Deserializer 
Basically here we are stopping the user to enter decimal point for integer type for rest api call --->>

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;

import java.io.IOException;

public class CustomIntegerDeserializer extends JsonDeserializer<Integer> {

    private static Logger logger = LoggerFactory.getLogger(CustomIntegerDeserializer.class);

    @Override
    public Integer deserialize(JsonParser p, DeserializationContext ctx)
         throws IOException,JsonProcessingException {
        logger.info("CustomIntegerDeserializer..............................");
        Double doubleVal = p.getDoubleValue();
        try {
            double ceil = Math.ceil(doubleVal);
            double floor = Math.floor(doubleVal);
            if((ceil-floor)>0) {
                String message = String.format("Cannot coerce a floating-point value ('%s') into Integer", doubleVal.toString());
                throw new Exception(message);
            }
            return Integer.valueOf(p.getIntValue());
        } catch (Exception exception) {
            logger.info("Exception in CustomIntegerDeserializer::{}",exception.getMessage());
      
            //throw new custom exception which are to be managed by exception handler
            
        }
    }

}

using on bean class-->
 @JsonDeserialize(using = CustomIntegerDeserializer.class)
    private Integer initRatePerSec = -1;

request-->
{
    .....
    "initRatePerSec": 5.1
}
response-->
{
    "statusCode": 400,
     ..............,
    "message": "JSON parse error: Cannot coerce a floating-point value ('5.1') into Integer; 
}
ktca8awb

ktca8awb6#

您必须在FlickrAccount中将URL设置为一个类,并为它给予一个_content字段

相关问题