简体   繁体   中英

Jackson vs Gson for simple deserialisation

For parsing JSON like this twitter API users/show response I've been using Jackson and Gson Java libraries as candidates to do this work. I'm only interested in a small subset of properties of the JSON so Gson was nice because of its very concise syntax but I'm losing an internal battle to continue to use Gson as Jackson is already used elsewhere in our application and it has documented better performance (which I concede are both good reasons to lose Gson).

For a POJO like

public class TwitterUser {
private String id_str;
private String screen_name;

public String getId_str() {
    return id_str;
}

public void setId_str(String id_str) {
    this.id_str = id_str;
}

public String getScreen_name() {
    return screen_name;
}

public void setScreen_name(String screen_name) {
    this.screen_name = screen_name;
}
}

The only code for Gson needed to build this is one line,

TwitterUser user = new Gson().fromJson(jsonStr, TwitterUser.class);

That's pretty nice to me; scales well and is opt-in for the properties you want. Jackson on the other hand is a little more laborious for building a POJO from selected fields.

Map<String,Object> userData = new ObjectMapper().readValue(jsonStr, Map.class);
//then build TwitterUser manually

or

TwitterUser user = new ObjectMapper().readValue(jsonStr, TwitterUser.class);
//each unused property must be marked as ignorable. Yikes! For 30 odd ignored fields thats too much configuration.

So after that long winded explanation, is there a way I can use Jackson with less code than is demonstrated above?

With Jackson 1.4+ you can use the class-level @JsonIgnoreProperties annotation to silently ignore unknown fields, with ignoreUnknown set to true.

@JsonIgnoreProperties(ignoreUnknown = true)
public class TwitterUser {
    // snip...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM