我在做項目使用Lucen庫在這裏我需要動態構建查詢使用Json對象。所以在這裏我使用拋棄庫。我的JSON這樣如何創建以下字符串動態
{"OR":{"OR": {"fildKey1": "value1","fildKey2": "value2","fildKeyabc": "valueabc"},"AND": {"AND": {"fildKey3": "value3","OR": {"fildKey4": "value4","fildKey5": "value5"}},"fildKeyw": "valuew"}}}
使用上述JSON一個例子,我需要創建下面的查詢
((fildKey1 : value1 OR fildKey2 : value2 OR fildKeyabc : valueabc)OR((fildKey3 : value3 AND(fildKey4 : value4 OR fildKey5 : value5))AND fildKeyw : valuew))
,但我不能得到上述query.my結果是這樣的
((fildKey1 : value1 OR fildKey2 : value2 OR fildKeyabc : valueabc)OR((fildKey3 : value3 AND(fildKey4 : value4 OR fildKey5 : value5)AND)AND fildKeyw : valuew)OR)
我需要刪除以上額外2運營商這是我的代碼
public class JettisionCls {
static Stack s = new Stack();
String operater = null;
static String res = "";
int bracket_counter = 0;
public void getKeyAndValue(JSONObject json_obj) throws JSONException{
Iterator<String> iter = json_obj.keys();
while (iter.hasNext()) {
String obj = iter.next();
if(obj.toLowerCase().equals("and") || obj.toLowerCase().equals("or")){
//System.out.print(obj);
operater = obj;
}
JSONObject temp = null;
try {
temp = new JSONObject(json_obj.get(obj).toString());
} catch (JSONException e) {
e.getStackTrace();
}
if (temp != null) {
//System.out.print("(");
res = res +"(";
bracket_counter=bracket_counter+1;
s.push(operater);
getKeyAndValue(temp);
//System.out.print(")");
res = res +")";
bracket_counter=bracket_counter-1;
if((s.size()) != 0 && bracket_counter != 0){
//System.out.print(s.peek());
s.pop();
res = res +s.peek();
}
else{
s.pop();
}
}
else{
if(iter.hasNext()){
res = res+" "+obj + " : " + json_obj.get(obj) + " " + operater; }
else{
res = res+" "+obj + " : " + json_obj.get(obj)+" ";
}
}
}
}
我的主要方法是這樣的
String multiLevelQuery = "{\"OR\":{\"OR\": {\"fildKey1\": \"value1\",\"fildKey2\": \"value2\",\"fildKeyabc\": \"valueabc\"},\"AND\": {\"AND\": {\"fildKey3\": \"value3\",\"OR\": {\"fildKey4\": \"value4\",\"fildKey5\": \"value5\"}},\"fildKeyw\": \"valuew\"}}}";
JSONObject jobj = new JSONObject(multiLevelQuery);
JettisionCls obj = new JettisionCls();
obj.getKeyAndValue(jobj);
System.out.println(JettisionCls.res);
如果任何人都可以請幫助我。
@Afrin這一個也適用於簡單的查詢。我也看不到在這裏有任何bug。如果它有請解釋更多。 – mssb 2012-07-30 04:20:56