Java Generic Jackson Type Reference

时间:2017-10-23 19:16:06

标签: java json jackson

我试图通过以下方式将ElasticSearch json设为Object。

ElasticResult<Record> records = ElasticUtils.getElasticResult("MyBeautifulJson");

public static <T> ElasticResult<T> getElasticResult(String json) throws Exception{
    ObjectMapper mapper = new ObjectMapper();
    return mapper.readValue(json, new TypeReference<ElasticResult<T>>(){});
}

哪个不起作用,但工作是什么

ElasticResult<Record> records = ElasticUtils.getElasticResult("MyBeautifulJson");
public static ElasticResult<Record> getElasticResult(String json) throws Exception{
    ObjectMapper mapper = new ObjectMapper();
    return mapper.readValue(json, new TypeReference<ElasticResult<Record>>(){});
}

这两个陈述应该是相同的吗?我不确定我做错了什么!如果有人能解释那将是伟大的:)。如果我需要发布更多代码,请告诉我。

编辑 - ElasticResult代码

public class ElasticResult<T> {
    private int took;
    private boolean timed_out;
    private Shard _shards;
    private Hits<T> hits;

    public int getTook() {
        return took;
    }

    public void setTook(int took) {
        this.took = took;
    }

    public boolean isTimed_out() {
        return timed_out;
    }

    public void setTimed_out(boolean timed_out) {
        this.timed_out = timed_out;
    }

    public Shard get_shards() {
        return _shards;
    }

    public void set_shards(Shard _shards) {
        this._shards = _shards;
    }

    public Hits<T> getHits() {
        return hits;
    }

    public void setHits(Hits<T> hits) {
        this.hits = hits;
    }
}


public class Hits<T> {
    private int total;
    private long max_score;
    private List<Hit<T>> hits;

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public long getMax_score() {
        return max_score;
    }

    public void setMax_score(long max_score) {
        this.max_score = max_score;
    }

    public List<Hit<T>> getHits() {
        return hits;
    }

    public void setHits(List<Hit<T>> hits) {
        this.hits = hits;
    }
}


public class Hit<T> {
    private String _index;
    private String _type;
    private String _id;
    private String _score;
    private T _source;

    public String get_index() {
        return _index;
    }

    public void set_index(String _index) {
        this._index = _index;
    }

    public String get_type() {
        return _type;
    }

    public void set_type(String _type) {
        this._type = _type;
    }

    public String get_id() {
        return _id;
    }

    public void set_id(String _id) {
        this._id = _id;
    }

    public String get_score() {
        return _score;
    }

    public void set_score(String _score) {
        this._score = _score;
    }

    public T get_source() {
        return _source;
    }

    public void set_source(T _source) {
        this._source = _source;
    }
}

0 个答案:

没有答案