gcube-cms-suite/geoportal-common/src/main/java/org/gcube/application/geoportal/common/utils/JSONPathWrapper.java

66 lines
2.2 KiB
Java

package org.gcube.application.geoportal.common.utils;
import com.jayway.jsonpath.*;
import lombok.Getter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class JSONPathWrapper {
public static Configuration JSON_PATH_ALWAYS_LIST_CONFIG=null;
public static Configuration JSON_PATH_PATHS_CONFIGURATION=null;
static {
JSON_PATH_ALWAYS_LIST_CONFIG= Configuration.builder().options(Option.ALWAYS_RETURN_LIST,Option.SUPPRESS_EXCEPTIONS,Option.DEFAULT_PATH_LEAF_TO_NULL).build();
JSON_PATH_PATHS_CONFIGURATION = Configuration.builder().options(Option.AS_PATH_LIST,Option.SUPPRESS_EXCEPTIONS,Option.DEFAULT_PATH_LEAF_TO_NULL).build();
}
@Getter
DocumentContext ctx=null;
public JSONPathWrapper(String json) {
ctx=JsonPath.using(JSON_PATH_ALWAYS_LIST_CONFIG).parse(json);
}
public List<Object> getByPath(String path){
return ctx.read(path);
}
public <T> List<T> getByPath(String path,Class<T> clazz){
return ctx.read(path, new TypeRef<List<T>>() {});
}
public JSONPathWrapper set(String path, Object toSet){
ctx.set(path,toSet);
return this;
}
// public static final DocumentContext addElement(DocumentContext ctx,String path) throws JsonPathException{
// JsonPath jPath=JsonPath.compile(path);
// if(jPath.isDefinite()) {
// String parent=path.substring(0,path.lastIndexOf("."));
// List<String> found=ctx.read(parent);
// if(found==null || found.size()==0 || found.get(0)==null) {
// //missing parent, use recursion
// addElement(ctx,parent);
// }
// // found parent, adding element
// String element=path.substring(path.lastIndexOf(".")+1);
//
// Object value=new HashMap<String,String>();
// if(element.contains("[")) {
// value=new ArrayList<Object>(Collections.singletonList(value));
//
// element=element.substring(0,element.indexOf("["));
// }
//
// ctx.put(parent, element, value);
// return ctx;
// }else throw new JsonPathException("Unable to initialize non-definite path : "+path);
// }
}