Python中文网

一个关于 编程问题的解答网站.

有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

jackson我如何用Java解析这个Json字符串

我的JSON字符串:

{ "categorySetName": "TSN", "rows": [ { "date": 201750, "rank1": { "label": "\uBC30\uACBD", "search_keyword": "\uBC30\uACBD", "frequency": 3975, "score": 69.27185 }, "rank2": { "label": "\uBC30\uACBD\uD654\uBA74", "search_keyword": "\uBC30\uACBD\uD654\uBA74", "frequency": 3736, "score": 109.83768 }, "rank3": { "label": "\uC544\uC774\uD3F0x", "search_keyword": "\uC544\uC774\uD3F0x", "frequency": 3382, "score": 62.057728 }, . . . . "rank500": { "label": "\uC544\uC774\uD3F0x", "search_keyword": "\uC544\uC774\uD3F0x", "frequency": 1572, "score": 68.057728 } } }

我的反序列化程序。爪哇


@SuppressWarnings("serial")
public class AssociationTopRowDeserializer extends StdDeserializer<AssociationTopRow> {

    public static final String DATE = "date";
    public static final List<String> knownFieldNames = Arrays.asList(DATE);

    public AssociationTopRowDeserializer() {
        this(null);
    }

    public AssociationTopRowDeserializer(Class<AssociationTopRow> c) {
        super(c);
    }

    @Override
    @SuppressWarnings("unchecked")
    public AssociationTopRow deserialize(JsonParser jsonParser, DeserializationContext desContext) throws IOException {
        AssociationTopRow row = new AssociationTopRow();
        JsonNode jsonNode = jsonParser.getCodec().readTree(jsonParser);
        ObjectMapper objectMapper = new ObjectMapper();

        row.setDate(jsonNode.get(DATE).asText());

        String unknownField = getUnknownField(jsonNode.fieldNames());
        if (unknownField != null) {
            Map<String, AssociationTopRowDetail> map = new HashMap<String, AssociationTopRowDetail>();
            map.put(unknownField, (AssociationTopRowDetail) objectMapper.convertValue(jsonNode.get(unknownField),
                    AssociationTopRowDetail.class));
            row.setTransMap(map);
        }
        return row;
    }

    public String getUnknownField(Iterator<String> fieldNames) {
        while (fieldNames.hasNext()) {
            String next = fieldNames.next();
            if (!knownFieldNames.contains(next))
                return next;
        }
        return null;
    }
}

这只显示有关“rank1”的信息


共 (1) 个答案

  1. # 1 楼答案

    您可以使用@JsonAnySetter注释,而不是自定义反序列化程序:

    public class AssociationTopRow {
    
        private String date;
        private final Map<String, AssociationTopRowDetail> details = new LinkedHashMap<>();
    
        // getter & setter for date
    
        @JsonAnySetter
        public void addDetail(String key, AssociationTopRowDetail detail) {
            details.put(key, detail);
        }
    
        @JsonAnyGetter
        public Map<String, AssociationTopRowDetail> getDetails() {
            return details;
        }
    
    }