javajackson:为什么我会得到jsonmappingexception,尽管我使用了@jsondeserialize

oewdyzsn  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(397)

我需要一些帮助Jackson图书馆在 java 。我有以下课程:

@JsonIgnoreProperties(ignoreUnknown = true) 
public class MarketHistoryData {
    private String countryCode;
    @JsonDeserialize(keyUsing = BpTimeDeserializer.class)
    private Map<BpTime, Double> hourToExpectedEngagePaidListings;
    @JsonDeserialize(keyUsing = BpTimeDeserializer.class)
    private Map<BpTime, Double> hourMinuteToExpectedEngagePaidListings;

    public MarketHistoryData() {}
    ...
    // getters and setters
}

我知道jackson很难反序列化一个键是对象的Map。因此,我添加了注解:

@JsonDeserialize(keyUsing = BpTimeDeserializer.class)

bptimedeserializer类是:

public class BpTimeDeserializer extends KeyDeserializer {

  private ObjectMapper mapper = new ObjectMapper();

  @Override
  public BpTime deserializeKey(String key, DeserializationContext ctxt) throws IOException {
    return mapper.readValue(key, BpTime.class);
  }
}

不过,在反序列化过程中我还是遇到了一个错误:

*****.uncheckedexecutionexception:com.fasterxml.jackson.databind.jsonmappingexception:无法识别的标记“com”:在[source:(string)处应为(json string、number、array、object或标记“null”、“true”或“false”)****bptime@5922062e[小时=1,分钟=0]“;行:1,列:1](通过引用链:**PACERCYCLOUTPUT[“campaignidtofactorcomputationdata”]->java.util.linkedhashmap[“1011620661”]->***factorcomputationdata[“selectedmarkethistorydataforcampaign”]->***markethistorydata[“HourtExpectedEngagePaidListings”])

你知道我能做些什么来克服这个错误吗?

rbpvctlc

rbpvctlc1#

我终于找到了解决这个错误的方法。

@JsonIgnoreProperties(ignoreUnknown = true)
public class MarketHistoryData {
    private String countryCode;
    @JsonDeserialize(keyUsing = BpTimeDeserializer.class)
    @JsonSerialize(keyUsing = BpTimeSerializer.class)
    private Map<BpTime, Double> hourToExpectedEngagePaidListings;
    @JsonDeserialize(keyUsing = BpTimeDeserializer.class)
    @JsonSerialize(keyUsing = BpTimeSerializer.class)
    private Map<BpTime, Double> hourMinuteToExpectedEngagePaidListings;
    ...
}

public class BpTimeDeserializer extends KeyDeserializer {

  private ObjectMapper mapper = new ObjectMapper();

  @Override
  public BpTime deserializeKey(String key, DeserializationContext ctxt) throws IOException {
    String[] keySplit = key.split(" ");
    BpTime bpTime = new BpTime();

    if (!keySplit[0].equals("-1")) {
      bpTime.setHour(Integer.parseInt(keySplit[0]));
    }
    if (!keySplit[1].equals("-1")) {
      bpTime.setMinute(Integer.parseInt(keySplit[1]));
    }
    return bpTime;
  }
}

public class BpTimeSerializer extends StdSerializer<BpTime> {

  public BpTimeSerializer() {
    this(null);
  }

  public BpTimeSerializer(Class<BpTime> t) {
    super(t);
  }

  @Override
  public void serialize(BpTime value, JsonGenerator generator, SerializerProvider arg2) throws IOException {
    generator.writeFieldName(String.format("%s %s", ofNullable(value.getHour()).orElse(-1),
        ofNullable(value.getMinute()).orElse(-1)));
  }
}

相关问题