Home > Java > javaTutorial > How can we parse nested JSON objects in Java?

How can we parse nested JSON objects in Java?

WBOY
Release: 2023-08-27 21:37:05
forward
787 people have browsed it

How can we parse nested JSON objects in Java?

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.

Syntax

String getString(int index)
Copy after login

Example

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
      }
   }
}
Copy after login

Output

abc123
xyz123
pqr123
mno123
jkl123
Copy after login

The above is the detailed content of How can we parse nested JSON objects in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template