在Java中解析JSON响应以提取值 [英] Parsing JSON Response in java to extract values
本文介绍了在Java中解析JSON响应以提取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想做的是得到响应,但不知道如何从中提取值.
What I'm trying to do is get a response, but don't know how to extract the values from it.
实际响应如下:
[
"SUCCESS",
[ [
"Karachi",
["کراچی"],
[],
{
"candidate_type": [0],
"is_confident": [true]
}
]]
]
我需要从中提取urdu
文本
String text = "Karachi";
String url = "https://inputtools.google.com/request";
try {
final HttpClient client = new HttpClient();
final PostMethod method = new PostMethod(url);
method.setParameter("text", text);
method.setParameter("itc", "ur-t-i0-und");
method.setParameter("num", "1");
method.setParameter("cp", "0");
method.setParameter("cs", "1");
method.setParameter("ie", "utf-8");
client.executeMethod(method);
BufferedReader strResponse = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(),"UTF-8"));
Object jObj = (Object) JSON.parse(strResponse);
推荐答案
尝试一下(您的缓冲区读取器可能有多行):
Try this (Your buffer reader may have more than one line):
StringBuilder yourJsonString= new StringBuilder();
String line;
while ((line = strResponse.readLine()) != null) {
yourJsonString.append(line);
}
JSONArray jsonObject = new JSONArray(yourJsonString.toString());
//retrieve the second element of json array
JSONArray secondElmArray= jsonObject.getJSONArray(1);
JSONArray innerArray = secondElmArray.getJSONArray(0);
JSONArray urduList= innerArray.getJSONArray(1);
String urduWord= urduList.getString(0);
这篇关于在Java中解析JSON响应以提取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文