JSON解析并将其存储在变量中

JSON解析并将其存储在变量中

问题描述:

我正在使用Wamp服务器创建数据库,并且已经能够以JSON格式在android studio中检索它们,但是我想将它们存储在变量中,并且WAMP中的数据库需要经常更新,所以我想要存储的数据为变量

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", 可用":"1" }, { "Pump":"Bhadrakali", 可用":"0" }, { "Pump":"Kumaripati", 可用":"0" }, { "Pump":"Balkhu", 可用":"1" } ] }

{ "server_response": [ { "Pump": "Sajha", "Available": "1" }, { "Pump": "Bhadrakali", "Available": "0" }, { "Pump": "Kumaripati", "Available": "0" }, { "Pump": "Balkhu", "Available": "1" } ] }

即,我想在Android Studio中在适用于某台泵"的可用值为1时执行某项任务,而当其为0时执行另一项任务,我该怎么做,请有人向我发送代码.

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.

首先将输出 json转换为JSONObject并通过子对象创建一个数组.再次将子级转换为Json对象并提取数据:

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}
}

如果您确定对象不为null,则也可以直接使用getString代替optString,因此您无需将其转换为toString()

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()