
更改
JSonObject objects = getArray.getJSonArray(i);
至
JSonObject objects = getArray.getJSonObject(i);
或者
JSonObject objects = getArray.optJSonObject(i);
取决于您使用的是JSON到/来自Java的库。(看起来
getJSONObject将为您工作。)
然后,要访问“对象”中的字符串元素,请
JSONObject按元素名称将其取出。
String a = objects.get("A");如果需要中的元素名称,则
JSONObject可以使用静态实用程序方法
JSONObject.getNames(JSONObject)来实现。
String[] elementNames = JSONObject.getNames(objects);
“获取第一个元素的值和最后一个元素的值。”
如果“ element”是指数组中的组件,请注意第一个组件在索引0处,最后一个组件在index处
getArray.length() - 1。
我想遍历数组中的对象并获取其组件和值。在我的示例中,第一个对象具有3个成分,scond具有5个成分,第三个具有4个成分。我想遍历它们中的每一个并获得其组件名称和值。
以下代码正是这样做的。
import org.json.JSONArray;import org.json.JSONObject;public class Foo{ public static void main(String[] args) throws Exception { String jsonInput = "{"JObjects":{"JArray1":[{"A":"a","B":"b","C":"c"},{"A":"a1","B":"b2","C":"c3","D":"d4","E":"e5"},{"A":"aa","B":"bb","C":"cc","D":"dd"}]}}"; // "I want to iterate though the objects in the array..." JSonObject outerObject = new JSonObject(jsonInput); JSonObject innerObject = outerObject.getJSonObject("JObjects"); JSonArray jsonArray = innerObject.getJSonArray("JArray1"); for (int i = 0, size = jsonArray.length(); i < size; i++) { JSonObject objectInArray = jsonArray.getJSonObject(i); // "...and get thier component and thier value." String[] elementNames = JSONObject.getNames(objectInArray); System.out.printf("%d ELEMENTS IN CURRENT OBJECT:n", elementNames.length); for (String elementName : elementNames) { String value = objectInArray.getString(elementName); System.out.printf("name=%s, value=%sn", elementName, value); } System.out.println(); } }}欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)