尝试writeValueAsString时抛出JsonProcessingException

时间:2016-03-16 01:02:38

标签: java json jackson

我是杰克逊的新手。我试图将POJO(普通的旧Java对象)序列化为JSON,并且我不断收到JsonProcessingException。我真的不明白为什么。我错过了什么吗?

public class Car {
    private String make;
    private String model;

    public String getMake() {
        return make;
    }

    public void setMake(String make) {
        this.make = make;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public Car (String make, String model) {
        this.make = make;
        this.model = model;
    }
}

然后我在其他地方......

try {
    Car car = new Car("honda", "accord");        

    String serialized;

    // enable pretty formatting
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    serialized = mapper.writeValueAsString(car);

    System.out.println(serialized);
} catch (JsonProcessingException e) {
    System.out.println("Failed to serialize the object to JSON");
}

我的输出只是

Failed to serialize the object to JSON

这里可能出现什么问题?我不明白如何抛出这个异常。

1 个答案:

答案 0 :(得分:2)

检查catch块中抛出异常中的消息以获取更多详细信息:

e.getMessage()

或只是刷新stacktrace

e.printStacktrace()