Skip to content

Instantly share code, notes, and snippets.

@satr
Created May 17, 2019 09:53
Show Gist options
  • Save satr/d25295e349015918d872ec6dec3c1054 to your computer and use it in GitHub Desktop.
Save satr/d25295e349015918d872ec6dec3c1054 to your computer and use it in GitHub Desktop.
Deserialize an object from JSON with Jackson lib
/*
https://github.com/FasterXML/jackson
Grade.build
dependencies {
compile group:'com.fasterxml.jackson', name:'jackson-bom', version: '2.9.8'
}
Input:
{ "first_name" : "John", "last_name" : "Smith" }
{ "first_name" : "John" }
{ "first_name" : "John", "some_prop" : "Some value" }
*/
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class JacksonDeserializeObject {
public Person getPerson(String json) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
try {
return objectMapper.readValue(json, Person.class);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
//----------------------------
import com.fasterxml.jackson.annotation.JsonProperty;
public class Person {
private String firstName;
private String lastName = null;
@JsonProperty("first_name")
public void SetFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return this.firstName;
}
@JsonProperty("last_name")
public void SetLastName(String lastName) { this.lastName = lastName; }
public String getLastName() {
return this.lastName;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment