我有以下格式的POST查询字符串:

param1 = aaa&inners [0] [“innerParam”] = bbb&inners [1] [“innerParam”] = nnn

我需要轻松将其转换为地图或POJO。

public class pojo{
private String param1;

private List<OtherPojo> inners;//array is also ok

//getters etc
}

class OtherPojo{
private String innerParam.

//getters etc
}

我以为可以通过Jersey @BeanParam或其他方式完成,但不幸的是这是不可能的。所以我只有一个字符串,需要将其编译为map或pojo。请注意,我不清楚如何解析此构造
inners[0]["innerParam"]

我不想手动进行。因此,我需要将其解析为一行。
Pojo p=someHelper.compileToPojo(postString);// or map

使用哪个库(如果存在)?

最佳答案

您可以使用的库是:com.fasterxml.jackson
以及如何实现它:

public void checkAndSetChildValues(ObjectNode node, String field, String value, ObjectMapper mapper) {
    int indexDot = field.indexOf('.');
    if (indexDot > -1) {
        String childFieldName = field.substring(0, indexDot);
        ObjectNode child = node.with(childFieldName);
        checkAndSetChildValues(child, field.substring(indexDot + 1), value, mapper);
    } else {
        try{
            node.set(field, mapper.convertValue(value, JsonNode.class));
        } catch(IllegalArgumentException ex){
            logger.debug("could not parse value {} for field {}", value, field);
        }
    }
}


public Object parse(Class type, String entityString) throws UnsupportedEncodingException {

    ObjectMapper mapper = mapperHolder.get();
    ObjectNode node = mapper.createObjectNode();
    Scanner s = new Scanner(entityString).useDelimiter("&|=");
    while (s.hasNext()) {
        String key = s.next();
        String value = s.hasNext() ? URLDecoder.decode(s.next(), "UTF-8") : null;
        checkAndSetChildValues(node, key, value, mapper);
    }
    Object result = mapper.convertValue(node, type);
    return result;
}

因此,您应该能够实现自己的javax.ws.rs.ext.MessageBodyReader,请参见:https://jersey.java.net/documentation/latest/message-body-workers.html#d0e7151

09-25 16:12