【问题标题】:Jackson throws JSONMappingException cannot be cast to java.lang.Comparable (through reference chain ***)Jackson throws JSONMappingException cannot be cast to java.lang.Comparable (通过引用链***)
【发布时间】:2019-02-07 04:52:41
【问题描述】:

我有一个 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
}

最后,Device定义为:

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: Device cannot be cast to java.lang.Comparable (通过引用链:Response["response"]->Response["devices"])

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

【问题讨论】:

  • 真的是implements Comparator&lt;device&gt;吗?那不应该编译。设备应该是大写的并且应该是可比较的。

标签: java json rest jackson


【解决方案1】:

你需要实现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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多