sách gpt4 ai đã đi

java - 使用fasterxml从JSON创建Java对象时出现异常

In lại 作者:行者123 更新时间:2023-12-02 04:26:56 27 4
mua khóa gpt4 Nike

我正在尝试使用 fastxml 和以下 JSON 构建 Java 对象

    JSON : {"name":"Location Test",
"location":{
"coordinates":[10.1234657,10.123467]
},
...
}

我收到此异常:

play.api.Application$$anon$1: Execution exception[[RuntimeException: com.fasterxml.jackson.databind.JsonMappingException:
Can not deserialize instance of double[] out of START_OBJECT token
at [Source: N/A; line: -1, column: -1] (through reference chain: com.mypackages.models.Place["location"])]]

地点类别:

public class Place{
private String name;
private Location location;
...
getters and setters
}

位置类别:

public class Location{
private double[] coordinates;

public Location(double[] coordinates) {
this.coordinates = coordinates;
}
...
//getter and setter for coordinate field
}

有人可以告诉我是什么原因导致了这个问题吗?

1 Câu trả lời

您需要从位置对象中删除构造函数。我已经根据您提供的信息创建了示例程序,并且运行成功。

位置类别:

public class Location{
private double[] coordinates;

/**
* @return the coordinates
*/
public double[] getCoordinates() {
return coordinates;
}

/**
* @param coordinates the coordinates to set
*/
public void setCoordinates(double[] coordinates) {
this.coordinates = coordinates;
}
}

地点类别:

public class Place{
private String name;
private Location location;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the location
*/
public Location getLocation() {
return location;
}
/**
* @param location the location to set
*/
public void setLocation(Location location) {
this.location = location;
}


@Ghi đè
public String toString() {
return "Place: " + name + " Location: " + Arrays.toString(location.getCoordinates());
}
}

APP类: 公开课App { public static void main(String[] args) 抛出 IOException {

      //read json file data to String
byte[] jsonData = Files.readAllBytes(Paths.get("places.txt"));

//create ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();

Place place = objectMapper.readValue(jsonData, Place.class);

System.out.println("Place Object\n"+ place);
}
}

Places.txt - 包含 JSON

{
"name":"Location Test",
"location":{
"coordinates":[10.1234657,10.123467]
}
}

您需要在 Maven 项目中包含以下依赖项:


com.fasterxml.jackson.core
jackson-databind
2.6.1

关于java - 使用fasterxml从JSON创建Java对象时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32032189/

27 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com