如何解析JSON数据提取目标属性为列表?Air应用Firebase数据处理疑问
Hey there! Let's tackle your questions one by one—sounds like you’ve built a neat IoT ecosystem with Android, Air, and ESP8266, and you’re just one step away from tying all the data together. Great job getting the Firebase data pulled already!
At its core, parsing JSON and grabbing specific properties boils down to three simple steps, no matter the language:
- Convert the raw JSON string into a native object/dictionary your code can work with
- Locate the target array (in your case, the
Lightsarray) - Loop through each item in that array, pull out the properties you need (
lightname,status,pin), and store them in a new list
Since you’re working with an Air app, I’ll assume you’re using ActionScript 3 (the standard for Air development). Let’s walk through a concrete example tailored to your setup.
First, Define a Light Class (Optional but Clean)
Creating a dedicated class to hold your light data will make your code more organized and easier to maintain:
class Light { public var lightname:String; public var status:String; public var pin:int; public function Light(lightname:String, status:String, pin:int) { this.lightname = lightname; this.status = status; this.pin = pin; } }
Parse Firebase JSON & Extract Your Lights
Assuming you’ve already fetched the JSON response from Firebase’s REST API, here’s how to process it:
// Replace this with your actual Firebase response string var firebaseResponse:String = '{"Lights": [{"lightname": "Living Room", "status": "on", "pin": 1}, {"lightname": "Bedroom", "status": "off", "pin": 2}]}'; // Step 1: Convert JSON string to a native object var jsonData:Object = JSON.parse(firebaseResponse); // Step 2: Get the Lights array from the parsed data var rawLightsArray:Array = jsonData.Lights; // Step 3: Extract properties into your custom Light list var extractedLights:Array = new Array(); for each(var lightEntry:Object in rawLightsArray) { // Add safety checks to handle missing properties (critical for real-world data!) var name:String = lightEntry.hasOwnProperty("lightname") ? lightEntry.lightname : "Unnamed Light"; var status:String = lightEntry.hasOwnProperty("status") ? lightEntry.status : "off"; var pin:int = lightEntry.hasOwnProperty("pin") ? parseInt(lightEntry.pin) : 0; // Create a Light object and add it to your list extractedLights.push(new Light(name, status, pin)); }
Handle Firebase’s Push ID Structure (If Needed)
If your Android app uses Firebase’s push() method to upload lights, your JSON structure might look like this (with unique keys instead of a straight array):
{ "Lights": { "-Nxyz789": {"lightname": "Kitchen", "status": "on", "pin": 3}, "-Nabc123": {"lightname": "Porch", "status": "off", "pin": 4} } }
No problem—just adjust the code to convert the key-value object into an array first:
var rawLightsObj:Object = jsonData.Lights; var rawLightsArray:Array = new Array(); // Loop through each key in the Lights object for(var key:String in rawLightsObj) { rawLightsArray.push(rawLightsObj[key]); } // Then proceed with the extraction loop as before!
Use the Extracted List for ESP8266 Socket Communication
Now that you have your extractedLights list, you can loop through it to send signals to your ESP8266. Here’s a quick snippet to illustrate:
// Assume you already have a connected Socket instance called espSocket for each(var light:Light in extractedLights) { // Format a message that ESP8266 can parse (adjust the format to match your ESP code!) var message:String = "PIN:" + light.pin + ",STATUS:" + light.status; // Send the message over the socket espSocket.writeUTFBytes(message + "\n"); // Add a newline to signal end of message espSocket.flush(); trace("Sent command to ESP: " + message); }
Quick Tips to Avoid Headaches
- Always validate data: Firebase data might have missing or malformed properties—use
hasOwnPropertyand default values to prevent crashes. - Match Socket message formats: Make sure the string you send to ESP8266 matches what its code expects (e.g., if ESP is looking for "PIN=1,STATUS=ON", adjust your message string accordingly).
- Test incrementally: First verify your JSON parsing works by tracing the extracted list, then add the Socket communication once that’s solid.
内容的提问来源于stack exchange,提问作者Danish Ajaib

