JSON解析并将其存储在变量中 [英] JSON Parsing and storing them in variables

查看:235
本文介绍了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()

这篇关于JSON解析并将其存储在变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆