实现字符串方式调用复杂json
传值 "freeform.test2[0].test3" 调用返回的是键 test3的值对象
思想是利用 for 中变量迭代
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.PrintStream;
public class Demo2 {
public static int getIndex(String str){
String indexSub = str.substring(str.indexOf("["));
return Integer.parseInt(indexSub.substring(1,indexSub.length()-1));
}
public static Object getVal(JSONObject js,String key){
System.out.println("js is:");
System.out.println(js.toString());
if(key.endsWith("]")){
int index = getIndex(key);
System.out.println("index is "+String.valueOf(index));
System.out.println("key is "+String.valueOf(key.substring(0,key.indexOf("["))));
System.out.println();
return js.getJSONArray(key.substring(0,key.indexOf("["))).get(index);
}else {
System.out.println("else key is "+key);
Object o = js.get(key);
System.out.println("o is "+o.toString());
return o;
}
}
public static Object getJsonVal(Object obj,String[] keyStr){
Object iter = getVal((JSONObject) obj, keyStr[0]);;
System.out.println("keyStr is:");
for (String s :
keyStr) {
System.out.print(s+"\t");
}
System.out.println("\n========================================");
if (keyStr.length==1){
System.out.println("iter is "+ iter.toString());
return iter;
}else {
for(int i=1;i<keyStr.length;i++){
if(iter instanceof JSONObject){
iter = getVal((JSONObject) iter,keyStr[i]);
}
}}
return iter;
}
public static void main(String[] args) {
String body = "{\n" +
" \"Content-Length\":\"87\",\n" +
" \"Content-Type\":\"application/json\",\n" +
" \"freeform\":{\n" +
" \"test1\":\"test1val\",\n" +
" \"test2\":[\n" +
" {\n" +
" \"test3\":\"test3val\"\n" +
" },\n" +
" {\n" +
" \"test4\":{\n" +
" \"test5\":\"test5val\",\n" +
" \"test6\":\"test6val\"\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
String str = "freeform.test2[0].test3";
Object jsonVal = getJsonVal(JSON.parseObject(body), str.split("\\."));
System.out.println("---------------------------------------");
System.out.println(jsonVal.toString());
}
}
|