I'm trying to get the hang of Jackson for JSON parsing by going through the toy examples here: http://wiki.fasterxml.com/JacksonInFiveMinutes
The JSON:
{
"name" : { "first" : "Joe", "last" : "Sixpack" },
"gender" : "MALE",
"verified" : false,
"userImage" : "Rm9vYmFyIQ=="
}
I'm having trouble with the "Raw" Data Binding snippets:
1 ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
2 Map<String,Object> userData = mapper.readValue(new File("user.json"), Map.class);
The value at "name" is {first=Joe, last=Sixpack}. Surely the raw data binding can handle nested JSON objects, but I can't figure out how to access the value of first and last. What am I doing wrong?
I know it's late but This is how I did it. Please see below.
MainClass.java=
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class MainClass {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String jsonStr = "{\r\n" + " \"name\" : { \"first\" : \"Joe\", \"last\" : \"Sixpack\" },\r\n"
+ " \"gender\" : \"MALE\",\r\n" + " \"verified\" : false,\r\n"
+ " \"userImage\" : \"Rm9vYmFyIQ==\"\r\n" + "}";
ObjectMapper mapper = new ObjectMapper();
EntityClass jsonObj = mapper.readValue(jsonStr, EntityClass.class);
System.out.println(jsonObj.getName().getFirst());
System.out.println(jsonObj.getName().getLast());
System.out.println(jsonObj.getGender());
System.out.println(jsonObj.getVerified());
System.out.println(jsonObj.getUserImage() + "\n");
}
}
EntityClass.java=
public class EntityClass
{
private String verified;
private Name name;
private String userImage;
private String gender;
public String getVerified ()
{
return verified;
}
public void setVerified (String verified)
{
this.verified = verified;
}
public Name getName ()
{
return name;
}
public void setName (Name name)
{
this.name = name;
}
public String getUserImage ()
{
return userImage;
}
public void setUserImage (String userImage)
{
this.userImage = userImage;
}
public String getGender ()
{
return gender;
}
public void setGender (String gender)
{
this.gender = gender;
}
@Override
public String toString()
{
return "ClassPojo [verified = "+verified+", name = "+name+", userImage = "+userImage+", gender = "+gender+"]";
}
}
Name.java=
public class Name {
private String last;
private String first;
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
@Override
public String toString() {
return "Name [last=" + last + ", first=" + first + "]";
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
} }
RESULT:- Joe Sixpack MALE false Rm9vYmFyIQ==
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.