0

我试图通过这里的玩具示例来了解杰克逊解析 JSON 的窍门: http ://wiki.fasterxml.com/JacksonInFiveMinutes

JSON:

{
  "name" : { "first" : "Joe", "last" : "Sixpack" },
  "gender" : "MALE",
  "verified" : false,
  "userImage" : "Rm9vYmFyIQ=="
}

我在使用“原始”数据绑定片段时遇到问题:

1 ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
2 Map<String,Object> userData = mapper.readValue(new File("user.json"), Map.class);

“name”处的值是 {first=Joe, last=Sixpack}。当然,原始数据绑定可以处理嵌套的 JSON 对象,但我不知道如何访问 first 和 last 的值。我究竟做错了什么?

4

1 回答 1

0

我知道已经晚了,但我就是这样做的。请看下文。

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");

}

}

实体类.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+"]";
}

}

名称.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;
} }

结果:- Joe Sixpack MALE 假 Rm9vYmFyIQ==

于 2018-12-27T05:41:36.287 回答