The JSON is a lightweight, text-based and language-independent data exchange format. The JSON can represent two structured types like objects and arrays. A JSONArray can parse text from a String to produce a vector-like object. We can parse a nested JSON object using the getString(index) method of JSONArray. This is a convenience method for the getJSONString(index).getString() method and it returns a string value at the specified position.
String getString(int index)
import java.util.*; import org.json.*; public class NestedJSONObjectTest { public static void main(String args[]) { String jsonDataString = "{userInfo : [{username:abc123}, {username:xyz123},{username:pqr123}, {username:mno123},{username:jkl123}]}"; JSONObject jsonObject = new JSONObject(jsonDataString); List<String> list = new ArrayList<String>(); JSONArray jsonArray = jsonObject.getJSONArray("userInfo"); for(int i = 0 ; i < jsonArray.length(); i++) { list.add(jsonArray.getJSONObject(i).getString("username")); System.out.println(jsonArray.getJSONObject(i).getString("username")); // display usernames } } }
abc123 xyz123 pqr123 mno123 jkl123
以上就是我们如何在Java中解析嵌套的JSON对象?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号