日期:2014-05-20  浏览次数:20637 次

求n层Map嵌套解析算法,算出Map表示的逻辑值
本帖最后由 jiacoo 于 2014-01-02 14:16:27 编辑
如下图是Map的json字符串形式,要算出该Map的最终逻辑值,or逻辑或关系,and逻辑与关系,如:or: ["true","false",]的结果为true。Map最里层是只会是List。
如果使用递归要只能用循环的方式来做,我要用这个的地方不能写函数。


{
or: {
    and: {
        or: [
            "true",
            "false",
        ],
        and: {
            and: [
                "false",
                "false"
            ],
            or: [
                "true",
                "false",
                "false"
            ]
        }
    }
    or: [
        "true",
        "false",
        "false"
    ],
}
}

------解决方案--------------------
一看这一类型的,大部分第一想法肯定是递归。递归的关键是在于什么时候是最后一层,这里面最后一层显然是为数组的情况,为数组的时候直接返回来true或false就行了,否则进入递归。

private boolean getResult(String flag,JSONObject jsonObject) throws Exception{
if(null != jsonObject && !jsonObject.isEmpty()){
JSONArray jsonArray = new JSONArray();
Iterator<Object> i = jsonObject.keys();
while(i.hasNext()){
String key = i.next().toString();
try {
JSONObject value = jsonObject.getJSONObject(key);
Json2Bool j2b = new Json2Bool();
if(j2b.getResult(key,value)){
jsonArray.add("true");
}else{
jsonArray.add("false");
}
} catch (Exception e) {
JSONArray value = jsonObject.getJSONArray(key);
jsonArray.add(str2Bool(key,value)+"");
}

}
return str2Bool(flag,jsonArray);
}else{
System.out.println("error:格式错误");
return false;

}
}


private boolean str2Bool(String flag,JSONArray list) throws Exception{
if(null == flag 
------解决方案--------------------
 null == list 
------解决方案--------------------
 list.size() == 0){
throw new BoolException();
}else{
if("or".equalsIgnoreCase(flag)){
boolean result = false;
for(int i=0;i<list.size();i++){
String value = list.get(i).toString();
if(str2Bool(value)){
result = true;
break;
}else{
continue;
}
}
return result;
}else if("and".equalsIgnoreCase(flag)){
boolean result = true;
for(int i=0;i<list.size();i++){
String value = list.get(i).toString();
if(str2Bool(value)){
continue;
}else{
result = false;
break;
}
}
return result;
}else{
throw new BoolException();
}
}
}

private boolean str2Bool(String str) throws Exception{
if(null  == str){
throw new BoolException();
}
if("true".equals(str)){
return true;
}else if("false".equals(str)){
return false;
}else{
throw new BoolException();
}
}