问题
I am using Wamp server to create a database, and i have been able to retrieve them in android studio in JSON format, but I want to store them in variables, and the database in WAMP needs to be updated often so i want the data to be stored it a variable
{ "server_response": [ { "Pump": "Sajha", "Available": "1" }, { "Pump": "Bhadrakali", "Available": "0" }, { "Pump": "Kumaripati", "Available": "0" }, { "Pump": "Balkhu", "Available": "1" } ] }
i.e, I want to perform a certain task when Available for a certain pump is 1 and a different task when it is 0 in android studio, how do i do it, can please someone send me the code.
回答1:
First convert the output json to a JSONObject and create an array through child objects. Again convert the children to Json objects and extract data:
String parentObject= new JSONObject(output);
String pumps= parentObject.optString("server_response").toString();
JSONArray childrenArray = new JSONArray(pumps);
for(int i=0; i < childrenArray.length(); i++)
{
JSONObject childObject = childrenArray.getJSONObject(i);
String Pump= childObject.optString("Pump").toString();
String Available= childObject.optString("Available").toString();
//if (Available.equals("1")){Do something}
}
You may also directly use getString
instead of optString
if you are sure that object is not null and so you wont need to convert it toString()
来源:https://stackoverflow.com/questions/37452165/json-parsing-and-storing-them-in-variables