[英]Android - Covert From JSON String to Java Object
I have Android app connected to MySQL database, everything works fine with the connection, but the data retrieved from database comes in JSON format, I use this class for connection: 我已经将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();
}
}
And I apply it like this: 我像这样应用它:
private void GetComments() {
new CommunicatetoServer().execute(SERVER_URL + "GetComments.php");
}
The method above is to retrieve all comments information from the database, and it comes in this way (the data is for test only): 上面的方法是从数据库中检索所有评论信息,并且这种方式是这样的(数据仅用于测试):
[{"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"}]
[{“ 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“}]
So how can I convert it to java object? 那么如何将其转换为Java对象呢?
Thank you. 谢谢。
如果要获取可以返回子代的JSONObject等,则可以使用JSON-Simple库:
JSONObject obj = (JSONObject) new JSONParser().parse(jsonString);
A JSON Object starts and ends with curly braces and JSON Array starts and ends with square brackets. JSON对象以大括号开头和结尾,而JSON Array以方括号开头和结尾。 What you have there is a JSON array.
您所拥有的是一个JSON数组。
If you want to print it out, you need to parse it. 如果要打印出来,则需要对其进行解析。 JSON is a key and value pair.
JSON是键和值对。 So for example
"Uname":"test3"
Uname is the key and test3 is the value. 因此,例如
"Uname":"test3"
Uname是键,而test3是值。
Look into HashMaps for JSON Arrays. 查看HashMaps中的JSON数组。
Here is an example I found from JSON Array iteration in Android/Java : 这是我在Android / Java中的JSON Array迭代中找到的示例:
HashMap<String, String> applicationSettings = new HashMap<String,String>();
for(int i = 0; i < settings.length(); i++){
String value = settings.getJSONObject(i).getString("value");
String name = settings.getJSONObject(i).getString("name");
applicationSettings.put(name, value);
}
Allow me to highly recommend you use a JSON -> Java Object mapper such as gson. 请允许我强烈建议您使用JSON-> Java Object映射器,例如gson。
This will allow you to simply map between the serialized json representation of the data and you java object model. 这将使您可以简单地在数据的序列化json表示形式与Java对象模型之间进行映射。
First define your model class: 首先定义您的模型类:
class Data {
String Uname;
Long Id;
String DateTime; // can convert to a Date using a TypeAdapter
String comment;
}
Then, use gson to parse your InputStream
into your data: 然后,使用gson将
InputStream
解析为数据:
is = getResponseEntity.getContent();
Gson gson = new Gson();
List<Data> data = gson.fromJson(new BufferedReader(is), new TypeToken<ArrayList<Data>>() {}.getType());
Now you can easily manipulate your data as you see fit using java objects. 现在,您可以使用Java对象轻松地调整您认为合适的数据。
Documentation for gson can be found here: gson的文档可以在这里找到:
Gson: https://code.google.com/p/google-gson/ Gson: https : //code.google.com/p/google-gson/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.