Before we begin, make sure you have the necessary JSON library. There are several options available, such as JSON.simple, Gson, or Jackson. For the purpose of this tutorial, we will use the JSON.simple library, which is lightweight and easy to use.
We will parse below JSON,
{
"name": "John Doe",
"age": "30",
"city": "New Jersey"
}
Import the JSON.simple Library to get started, you need to import the JSON.simple library into your project. If you are using Maven, add the following dependency to your project's pom.xml file.
xml<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
parse the provided JSON using JSONParser and print all the key sets using an iterator:
javaimport org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.util.Iterator;
public class JSONParsingExample {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John Doe\",\"age\":\"30\",\"city\":\"New Jersey\"}";
// Parse the JSON string
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(jsonString);
JSONObject jsonObject = (JSONObject) obj;
// Get an iterator for the key set
Iterator iterator = jsonObject.keySet().iterator();
// Iterate and print all key sets
while (iterator.hasNext()) {
String key = (String) iterator.next();
System.out.println(key);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
When you run this program, you will see the following output:
Each key in the JSON object will be printed on a separate line, just as before.name age city
If you want to print values you can use below,
java // Get an iterator for the values
Iterator iterator = jsonObject.values().iterator();
// Iterate and print all values
while (iterator.hasNext()) {
Object value = iterator.next();
System.out.println(value);
}
When you run this program, you will see the following output:
outputJohn Doe
30
New Jersey
No comments:
Post a Comment