I have POST query string with the following format:
param1=aaa&inners[0]["innerParam"]=bbb&inners[1]["innerParam"]=nnn
I need to easily convert it to a map or POJO.
public class pojo{
private String param1;
private List<OtherPojo> inners;//array is also ok
//getters etc
}
class OtherPojo{
private String innerParam.
//getters etc
}
I thought it might be done by Jersey @BeanParam or sth else, but unfortunately it's not possible. So I just have a string and need to compile it to map or pojo. Please note that it's not clear for me how to parse this construction
inners[0]["innerParam"]
I wouldn't like to do it manually. So I need to parse it desirable in one line.
Pojo p=someHelper.compileToPojo(postString);// or map
Which lib to use, if exists?
the library you could use is: com.fasterxml.jackson
and here how it could be implemented:
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;
}
So you should be able to implement an own javax.ws.rs.ext.MessageBodyReader
see: https://jersey.java.net/documentation/latest/message-body-workers.html#d0e7151