我有這個矩陣聊天機器人,我用Java製作爲響應的知識庫:通過JSON文件搜索有效
String[][] knowledgeBase={
{"hi","hello","howdy","hey"},//input 1; if you user inputs any of these,
{"hi","hello","hey"},//output 1; randomly choose between these as a response
{"how are you", "how r u", "how r you", "how are u"},//input 2; if you user inputs any of these,
{"good","doing well"},//output 2; randomly choose between these as a response
{"shut up","i dont care","stop talking"}//if input was in neither array, use one of these as a response
這是工作正常,當我有java文件裏面的基質。我做了一個JSON文件(我是新來的JSON所以不是很肯定,如果我得到了格式正確的),它類似於矩陣:
{
"0":{
"input":[""]
"output":["shut up","i dont care","stop talking"]
}
"1":{
"input":["hi","hello","howdy","hey"]
"output":["hi","hello","hey"]
}
"2":{
"input":["how are you", "how r u", "how r you", "how are u"]
"output":["good","doing well"]
}
}
這是我經歷的矩陣尋找一個精確匹配碼的輸入:
public void actionPerformed(ActionEvent e){
//get the user input
String quote=input.getText();
input.setText("");
if(!quote.equals("")){
addText("You:\t"+quote);
quote.trim();
while(quote.charAt(quote.length()-1)=='!' || quote.charAt(quote.length()-1)=='.' || quote.charAt(quote.length()-1)=='?'){
quote=quote.substring(0,quote.length()-1);
}
quote.trim();
byte response=0;
int j=0;
//check the knowledgeBase for a match or change topic
while(response==0){
//if a match is found, reply with the answer
if(inArray(quote.toLowerCase(),knowledgeBase[j*2])){
response=2;
int r=(int)Math.floor(Math.random()*knowledgeBase[(j*2)+1].length);
addText("\nPollockoraptor:\t"+knowledgeBase[(j*2)+1][r]);
}
j++;
//if a match is not found, go to change topic
if(j*2==knowledgeBase.length-1 && response==0){
response=1;
}
}
//change topic if bot is lost
if(response==1){
int r=(int)Math.floor(Math.random()*knowledgeBase[knowledgeBase.length-1].length);
addText("\nPollockoraptor:\t"+knowledgeBase[knowledgeBase.length-1][r]);
}
addText("\n");
}
}
public boolean inArray(String in,String[] str){
boolean match=false;
//look for an exact match
for(int i=0;i<str.length;i++){
if(str[i].equals(in)){
match=true;
}
}
return match;
}
如何通過具有類似功能的JSON文件進行搜索?我也可以在JSON文件整數而不是字符串中編號嗎?對不起,如果這是一個非常明顯的問題...我花了過去一小時試圖找出如何做到這一點。感謝您的幫助:)
看看[這篇文章](http://stackoverflow.com/questions/18983185/how-to-create-correct-jsonarray-in-java-using-jsonobject)幫助任何。 – 2014-10-07 05:07:13