我有以下字符串作为HTTPResponse。它是JSON格式。
[
{
"From":"en",
"OriginalTextSentenceLengths":[
5
],
"TranslatedText":"Hallo",
"TranslatedTextSentenceLengths":[
5
]
},
{
"From":"en",
"OriginalTextSentenceLengths":[
8
],
"TranslatedText":"Frage",
"TranslatedTextSentenceLengths":[
5
]
},
{
"From":"en",
"OriginalTextSentenceLengths":[
6
],
"TranslatedText":"Antwort",
"TranslatedTextSentenceLengths":[
7
]
}
]
因此,我按如下方式解析此字符串,以获得“翻译文本数组”
String resp = "[{\"From\":\"en\",\"OriginalTextSentenceLengths\":[5],\"TranslatedText\":\"Hallo\",\"TranslatedTextSentenceLengths\":[5]},{\"From\":\"en\",\"OriginalTextSentenceLengths\":[8],\"TranslatedText\":\"Frage\",\"TranslatedTextSentenceLengths\":[5]},{\"From\":\"en\",\"OriginalTextSentenceLengths\":[6],\"TranslatedText\":\"Antwort\",\"TranslatedTextSentenceLengths\":[7]}]";
String[] stringArray = null;
try {
JSONArray finalResult=null;
JSONTokener tokener = new JSONTokener(resp);
finalResult = new JSONArray(tokener);
stringArray = new String[finalResult.length()];
for(int i=0;i<finalResult.length();i++){
JSONObject e = finalResult.getJSONObject(i);
Log.v("TAG",e.getString("TranslatedText"));
stringArray[i]=e.getString("TranslatedText");
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我正在从JSON对象中获取提取的“翻译后的文本”数组(Hallo,Frage,Antwort)...
但是,当我通过直接向JSONTokener输入相同的字符串作为输入来执行相同的过程时,即在获得如下所示的HttpResponse之后,我在finalResult = new JSONArray(tokener)行中获取了JSON异常....
org.json.JSONException:输入的结尾(字符为0)
String resp = getHttpResponse(uri);
String[] stringArray = null;
try {
JSONArray finalResult=null;
JSONTokener tokener = new JSONTokener(resp);
finalResult = new JSONArray(tokener);
stringArray = new String[finalResult.length()];
for(int i=0;i<finalResult.length();i++){
JSONObject e = finalResult.getJSONObject(i);
Log.v("TAG",e.getString("TranslatedText"));
stringArray[i]=e.getString("TranslatedText");
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我已经尝试了2天,但无法解决此错误。.所以我将其发布在这里...请帮助
编辑:
我正在添加getHttpResponse的实现
public static String getHttpResponse(URI uri) {
Log.d("APP_TAG", "Going to make a get request");
StringBuilder response = new StringBuilder();
try {
HttpGet get = new HttpGet();
get.setURI(uri);
//DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 30000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 30000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
Log.v("TAG","1");
HttpResponse httpResponse = httpClient.execute(get);
Log.v("TAG","2");
if (httpResponse.getStatusLine().getStatusCode() == 200) {
Log.d("demo", "HTTP Get succeeded");
HttpEntity messageEntity = httpResponse.getEntity();
InputStream is = messageEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
response.append(line);
}
}
} catch (Exception e) {
Log.e("demo", e.getMessage());
}
Log.d("demo", "Done with HTTP getting");
return response.toString();
}
我给getHttpResponse的uri如下
String[] texts = {"hello","question","answer"};
final String params = "appId=" + URLEncoder.encode("78280AF4DFA1CE1676AFE86340C690023A5AC139","UTF-8")
+ "&from=" + URLEncoder.encode("en","UTF-8")
+ "&to=" + URLEncoder.encode("de","UTF-8")
+ "&texts=" + URLEncoder.encode(buildStringArrayParam(texts),"UTF-8");
final URL url = new URL("http://api.microsofttranslator.com/V2/Ajax.svc/TranslateArray?" + params);
URI myURI = java.net.URI.create(url.toString());
String resp = getHttpResponse(myURI);
此响应字符串是我要解析的内容...
这是针对buildStringArrayParam(texts)
StringBuilder targetString = new StringBuilder("[\"");
String value;
for(Object obj : values) {
if(obj!=null) {
value = obj.toString();
if(value.length()!=0) {
if(targetString.length()>2)
targetString.append(",\"");
targetString.append(value);
targetString.append("\"");
}
}
}
targetString.append("]");
return targetString.toString();
最佳答案
啊哈...微软。
至少在这种情况下,它们在开始时使用(错误?)FEFF FEFF
UTF-16 byte order mark来提供其API响应,这会破坏大多数客户端。
像the PHP guys over here already found out一样,您只需要从响应中除去前两个字节。对于代码中的示例:
JSONTokener tokener = new JSONTokener(resp.substring(2));
恐怕更无害的
trim()
不起作用。真的很难找到,因为
FEFF
的正式名称是“零宽度不间断空格”,因此它是完全不可见的,除非您将字符串视为char数组,或者注意到当您使用左/右箭头键...请注意,您不应使用收到的任何其他HTTP响应来执行此操作,这仅适用于此Microsoft API(也可以是其他API)。