我有 Android 应用程序连接到 MySQL 数据库,连接一切正常,但从数据库检索的数据采用 JSON 格式,我使用此类进行连接:
public class CommunicatetoServer extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String response = "";
String url = params[0];
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
HttpResponse getResponse = httpClient.execute(httpPost);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
is = getResponseEntity.getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
Log.d("IO", e.getMessage().toString());
e.printStackTrace();
}
// return JSON String
return response;
}
protected void onPostExecute(String response)
{
//onPostExecute
Log.d("Server Response : ", response.toString());
Toast.makeText(context, response.toString(), Toast.LENGTH_LONG).show();
}
}
我这样应用它:
private void GetComments() {
new CommunicatetoServer().execute(SERVER_URL + "GetComments.php");
}
上面的方法是从数据库中取出所有的评论信息,是这样的(数据仅供测试):
[{"Uname":"test1","Id":"1","DateTime":"2015-03-04 00:00:00","comment":"Hello"},{"Uname":"test3","Id":"1","DateTime":"2015-02-04 10:23:42","comment":"asdffgsdg asdf"}]
那么如何将其转换为java对象呢?
谢谢。
最佳答案
如果你想获得一个可以返回子对象等的 JSONObject,你可以使用 JSON-Simple 库:
JSONObject obj = (JSONObject) new JSONParser().parse(jsonString);
关于java - Android - 从 JSON 字符串转换为 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29335949/