Java 解析 JSON 数据并提取特定属性值
如何用Java代码解析JSON数组并取出name等于'temperature'的value值
可以使用 Java 中的 JSONObject 和 JSONArray 类来解析 JSON 数据,具体代码如下:
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonParseExample {
public static void main(String[] args) {
String jsonStr = '{"properties":[{"name":"mode","value":null},{"name":"temperature","value":"47"},{"name":"windspeed","value":null},{"name":"powerstate","value":"on"}]}';
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray propertiesArr = jsonObj.getJSONArray("properties");
for (int i = 0; i < propertiesArr.length(); i++) {
JSONObject propertyObj = propertiesArr.getJSONObject(i);
String name = propertyObj.getString("name");
if (name.equals("temperature")) {
String value = propertyObj.getString("value");
System.out.println("Temperature value is: " + value);
}
}
}
}
首先将 JSON 字符串转换为 JSONObject 对象,然后通过 getJSONArray() 方法获取到 properties 数组,遍历数组中的每个元素,判断 name 是否为 'temperature',如果是,则获取其对应的 value 值并输出。
原文地址: https://www.cveoy.top/t/topic/oDJi 著作权归作者所有。请勿转载和采集!