杰克逊抛出JSONMappingException不能强制转换为java.lang.Comparable(通过引用链***)

时间:2019-02-07 04:52:41

标签: java json rest jackson

我有一个JSON字符串。我正在使用杰克逊的ObjectMapper对其进行转换。 这是JSON字符串。

{
  "stat": "OK",
  "response": {
    "result": "auth",
    "status_msg": "Account is active",
    "devices": [
      {
        "device": "DPFZRS9FB0D46QFTM891",
        "type": "phone",
        "number": "XXX-XXX-0100",
        "name": "",
        "capabilities": [
            "auto",
            "push",
            "sms",
            "phone",
            "mobile_otp"
        ]
      },
      {
        "device": "DHEKH0JJIYC1LX3AZWO4",
        "type": "token",
        "name": "0"
      }
    ]
  }
}

我已经定义了一个对象,例如:

public class MyClass{
  private String stat;
  private Response response;
  //getters and setters
}

然后我将响应定义为:

public class Response{
  private String result;
  private String statusMsg;
  private SortedSet<Device> devices = new TreeSet<Device>();
  //getters and setters
}

最后,设备定义为:

public class Device implements Comparator<device>{
  private String device;
  private String number;
  // etc variables
  @Override
public int compareTo(Device o) {
    // TODO Auto-generated method stub
    return o.getNumber().compareTo(this.number);
}

最后,当我使用映射器时:

mapper.readValue(json.getBytes(), MyClass.class);

我得到这个异常: org.codehaus.jackson.map.JsonMappingException:无法将设备转换为java.lang.Comparable(通过参考链:Response [“ response”]-> Response [“ devices”])

在这种情况下,我应该怎么做才能实现sortedset设备数组?

1 个答案:

答案 0 :(得分:0)

您需要实现java.lang.Comparable接口。或为TreeSet构造函数提供比较器。

class Device implements Comparable<Device> {

    private String device;
    private String number;

    @Override
    public int compareTo(Device o) {
        return o.number.compareTo(this.number);
    }
}

或向Comparator提供TreeSet实例:

TreeSet<Device> devices = new TreeSet<>(new Comparator<Device>() {
    @Override
    public int compare(Device o1, Device o2) {
        return o1.getNumber().compareTo(o2.getNumber());
    }
});

Java 8起:

TreeSet<Device> devices = new TreeSet<>((d1, d2) -> d1.getNumber().compareTo(d2.getNumber()));

甚至更好一点:

TreeSet<Device> devices = new TreeSet<>(Comparator.comparing(Device::getNumber));