杰克逊:在自定义字段JsonDeserializer中获取整个对象

时间:2016-02-02 15:14:01

标签: java json jackson json-deserialization

我有这堂课:

@JsonIgnoreProperties(ignoreUnknown = true)
public class VehicleRestModel implements RestModel<Article> {

    @JsonProperty("idVehicle")
    public String id;

    public String name;
}

我从REST API获取此JSON:

[
  { "idVehicle" : "1234DHR", "tm" : "Hyundai", "model" : "Oskarsuko"},
  //more vehicles
]

我希望我的模型字段name是JSON的字段tmmodel连接在一起。我虽然使用了JsonDeserializer但是,我怎样才能获得整个JSON对象?

class MyDeserializer implements JsonDeserializer<String, String> {

    @Override
    public String deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        // I need the entire JSON here, in order to concatenate two fields
    }
}

谢谢!

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题,你可以让2个setter在同一个私有字段上工作,然后你可以用@JsonProperty而不是字段来标记setter。 这可以帮助您:@JsonProperty annotation on field as well as getter/setter

您也可以使用@JsonGetter(&#34; var&#34;)和@JsonSetter(&#34; var&#34;)代替@JsonProperty。

编辑:好的,一个解决方案。它是我提交过的最丑陋的代码,但如果你想要一个快速的东西而且你无法真正修改POJO原始界面(字段,getter)

    Template.add_review.events({
        'submit .add-review':function(event){
            event.preventDefault();
            var rating = event.target.rating.value;
            var review = event.target.review.value;
            var recipeId = Router.current().data()._id;
            Meteor.call('addReview',rating,review,recipeId);
        }
    });
Template.recipes.events({
    "click [data-action='addLikes']": function (event) {
        event.preventDefault();
        var recipe = Recipes.findOne({_id: this._id});
        Meteor.call('upvote',recipe)
    }
});

如果您在意,请注意空值,因为它们会在此演示代码中作为文字附加。