Skip to content

Instantly share code, notes, and snippets.

@itzg
Created January 14, 2021 19:30
Show Gist options
  • Save itzg/71e5417aefe4c3ab2691afd4f26a4e36 to your computer and use it in GitHub Desktop.
Save itzg/71e5417aefe4c3ab2691afd4f26a4e36 to your computer and use it in GitHub Desktop.
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.StringJoiner;
class TryReadTreeAndConvert {
static class Place {
String city;
String state;
public String getCity() { return city; }
public void setCity(String city) { this.city = city; }
public String getState() { return state; }
public void setState(String state) { this.state = state; }
public String toString() {
return new StringJoiner(", ", Place.class.getSimpleName() + "[", "]")
.add("city='" + city + "'")
.add("state='" + state + "'")
.toString();
}
}
public static void main(String[] args) throws JsonProcessingException {
final ObjectMapper objectMapper = new ObjectMapper();
final JsonNode tree = objectMapper.readTree("{\n"
+ " \"place\": {\n"
+ " \"city\": \"Dallas\",\n"
+ " \"state\": \"Texas\"\n"
+ " }\n"
+ "}");
final Place place = (Place) objectMapper.convertValue(tree.get("place"), Place.class);
System.out.println(place);
}
}
@itzg
Copy link
Author

itzg commented Jan 14, 2021

Outputs:

Place[city='Dallas', state='Texas']

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment