我正在使用非官方的姜语法检查API,它在json中返回结果。我想提取它作为输入提供的文本中给出的修正。
我已经完成了,但它只能作为静态工作,即我必须手动调整代码然后返回输出。
以下是我的代码 -
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONString;
//import org.json.simple.JSONObject;
import org.json.JSONObject;
import com.jayway.jsonpath.JsonPath;
import org.json.simple.parser.*;
public class Demo {
static class urllib {
public static StringBuffer urlopen(URL url) {
try {
//URL u = new URL(url);
StringBuffer sb = new StringBuffer();
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String str = null;
while((str = in.readLine())!=null) {
sb.append(str);
}
in.close();
return sb;
} catch(MalformedURLException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
return null;
}
}
public static void main(String[] args) {
StringBuffer result = null;
String finalResult = null;
StringBuffer response;
String finalResponse = null;
String finalText=null;
try{
//connections settings
String data = new String("a apple");
finalText=data;
String s[]=data.split(" ");
int i=0;
String text =s[0] ;
for(i=1;i<s.length;i++)
{
text=text+"+"+s[i];
}
System.out.println(text);
String Finaldata= new String(""+text);
URL url = new URL("http://services.gingersoftware.com/Ginger/correct/json/GingerTheText?lang=US&clientVersion=2.0&apiKey=XXXXXX-XXXX-XXXX-XXXX&text="+Finaldata);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.setDoOutput (true);
con.setRequestMethod("POST");
System.out.println("connection done");
JSONObject json ;
JSONParser parser = new JSONParser();
try
{
response =urllib.urlopen(url);
finalResponse= response.toString();
//System.out.println("final response"+finalResponse);
json = new JSONObject(finalResponse);
//System.out.println(json);
finalResult=json.toString();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
//This stores corrected text
String temp = new JSONObject(finalResult)
.getJSONArray("LightGingerTheTextResult").getJSONObject(0)
.getJSONArray("Suggestions").getJSONObject(0)
.getString("Text");
System.out.println(temp);
//This stores which part is corrected
String temp1 = new JSONObject(finalResult)
.getJSONArray("LightGingerTheTextResult").getJSONObject(0)
.getJSONArray("Suggestions").getJSONObject(1)
.getString("Text");
System.out.println(temp1);
temp=temp.toLowerCase();
temp1=temp1.toLowerCase();
String newString= finalText.replace(temp1, temp);
System.out.println(newString);
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
每次我需要更改&#34; getJsonObject()&#34;的值每次。有没有什么方法可以动态地执行此操作或以任何其他方式提取文本,如将json对象转换为java对象,但我对此没有任何了解。
谢谢。