ObjectMapper-无法反序列化实例java.lang.Double

时间:2016-06-15 22:10:36

标签: java android json jackson

我想从Node.js发送的字符串中获取该代码的数据:

User[] user2 = mapper.readValue(resultPayload, User[].class); 

我的用户类:

public class User {
    private double lat;
    private double lon;

    public User() {
    }

    public User(double lat, double lon) {
        this.lat = lat;
        this.lon = lon;
    }

    public double getLocationLat(){return lat;}

    public void setLocationLat(double lat){this.lat = lat;}

    public double getLocationLon(){return lon;}

    public void setLocationLon(double lon){this.lon = lon;}

}

但我收到了这样的警告:

WARNING: could not load Java7 Path class
/com.amazon.mysampleapp W/System.err: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.Double out of START_OBJECT token

我的JSON字符串包含:

[{"locationLon":{"N":"16.946397721767426"},"locationLat":{"N":"52.447558225994904"}},{"locationLon":{"N":"16.88841037452221"},"locationLat":{"N":"52.44599882989592"}},{"locationLon":{"N":"16.94861490279436"},"locationLat":{"N":"52.44514319230585"}}]

1 个答案:

答案 0 :(得分:0)

第1步:Location.java

import com.fasterxml.jackson.annotation.JsonProperty;

public class Location {
private double N;
public Location() {
  }
public Location(double n) {
    N = n;
  }
@JsonProperty("N")
public double getN() {
    return N;
  }
public void setN(double n) {
    N = n;
  }
@Override
public String toString() {
    return "N=" + N;
  }
}

第2步:User.java

public class User {
private Location locationLat;
private Location locationLon;

public User() {
  }
public User(Location locationLat, Location locationLon) {
    super();
    this.locationLat = locationLat;
    this.locationLon = locationLon;
  }
public Location getLocationLat() {
    return locationLat;
  }
public void setLocationLat(Location locationLat) {
    this.locationLat = locationLat;
  }
public Location getLocationLon() {
    return locationLon;
  }
public void setLocationLon(Location locationLon) {
    this.locationLon = locationLon;
  }
@Override
public String toString() {
    return "User [locationLat=" + locationLat + ", locationLon=" + locationLon + "]";
  } 
}

第3步:

String resultPayload=new String(Files.readAllBytes(new File("D:/test3.json").toPath()));
ObjectMapper mapper = new ObjectMapper();
User[] users = mapper.readValue(resultPayload, User[].class); 
System.out.println(Arrays.toString(users));

请考虑进行以上所有更改并查看结果。