1

我有以下字符串作为 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();
4

4 回答 4

3

啊哈哈...微软。

至少在这种情况下,他们在开始时使用(不正确的?)FEFF FEFFUTF-16字节顺序标记来提供 API 响应,这会破坏大多数客户端。

就像这里的 PHP 人已经发现一样,您只需从响应中删除前两个字节。例如在您的代码中:

JSONTokener tokener = new JSONTokener(resp.substring(2));

恐怕越无害的trim()也行不通。

真的很难找到,因为FEFF的正式名称是“零宽度不间断空格”,所以它是完全不可见的,除非您将字符串视为 char 数组或注意到当您使用左/右移动穿过字符串时文本光标如何停止方向键...

请注意,您不应该对收到的任何其他 HTTP 响应执行此操作,这仅适用于此 Microsoft API(也可能是其他 API)。

于 2012-04-18T11:51:19.760 回答
2

Try GSON

And try to change your code design, hope it will help you.

And retrieve content from url -

public static String getContent(String url) throws Exception {
    return(new Scanner(new URL(url).openConnection().getInputStream()).useDelimiter("/z").next());
}

Have fun...

于 2012-04-17T10:29:23.833 回答
0

尝试使用这个:

HttpPost request = new HttpPost(URL);
HttpResponse response = httpClient.execute(request);

HttpEntity httpEntity = response.getEntity();
InputStream content = httpEntity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(content,"iso-8859-1"),8);
String resp = reader.readLine();

现在“resp”将保存可以解析的字符串......

于 2012-04-17T10:01:32.583 回答
0
After getting the HTTP Response you have to do this thing, you cant use Httpresponse directly.

HttpResponse response= null;
response = http.execute(get);
HttpEntity entity = response.getEntity();
String xmlstring = EntityUtils.toString(entity);
message = xmlstring;
于 2012-04-17T10:46:16.373 回答