JSON到java对象的returing LinkedHashMap

时间:2016-03-10 06:59:11

标签: java json jackson

我有以下json字符串: -

{"name":"Test","sortlist":[],"filterlist":[{"fieldname":"regions_id","operator":"equals","value":{"id":1,"code":"HIGH","description":"HIGH Region","comment":"High Region","active":true}}]}

和Java类如下: -

@JsonSerialize
@JsonDeserialize
public class ItemFilter implements Serializable {

    private String name;
    private List<FieldFilter> filterlist = new ArrayList<FieldFilter>();

}

public class FieldFilter  implements Serializable {

    private static final long serialVersionUID = 1L;

    private String fieldname;
    private String operator;
    private Object value;
}

和我的转换方法如下: -

public static ItemFilter convertItemFilter(String item) {
        ObjectMapper mapper = new ObjectMapper();

        try {
            ItemFilter itemFilter = mapper.readValue(item, new TypeReference<ItemFilter>(){});
            return itemFilter;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
}

ItemFilter域名正在正确转换,但在private Object value;字段中我得到LinkedHashMap我想获得一个简单的对象,之后我会输入它。

有人可以指导我如何逃避LinkedHashMap并在变量中获得一个简单的Java Object吗?

我不能使用硬编码对象类型,因为它是一个通用的pojo,可以有任何对象类型。硬编码将使这个pojo更大,前端也需要改变它。这就是为什么我使用Object作为数据类型。

1 个答案:

答案 0 :(得分:-1)

以下类结构应将JSON返回到“YourObject”

public class YourObject{
  private String name;
  private List<String> sortList;
  private List<Filter> filterList;

public static class Filter{
  private String fieldname;
  private String operator;
  private Value value;

}
public static class Value{
  private Integer id;
  private String code;
  private String description;
  private String comment;
  private Boolean active;
}
}

然后使用以下内容将其读入对象:

YourObject itemFilter = mapper.readValue(item, YourObject.class);