How to convert string to JSON array in java

What you will learn here about java

  • How to convert string to JSONarray in java

While working with json, sometimes we come to situation where we need to convert String into Json array or string into entryset or string into Json Object. Here we will see how to convert String into entryset or String into Json array or String into Json Object

How to convert string to JSON array in java

Please follow the following steps to know how to convert string to json array in java
1)First create a simple maven project

2)Then add gson and json simple dependency in pom.xml which are given below


3)Now use following code which will convert String into Json array or entryset or Json object

import java.util.Map;
import java.util.Set;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class String2JsonArrayMain {

	public static void main(String[] args) {
		String input ="[\r\n"
				+ "  {\r\n"
				+ "    \"firstName\": \"John\",\r\n"
				+ "    \"latsName\": \"Dow\",\r\n"
				+ "    \"age\": 27,\r\n"
				+ "    \"gender\": \"male\"\r\n"
				+ "  }\r\n"
				+ "]";
		JSONParser parser = new JSONParser();
		try {
			Object object = (Object) parser.parse(input);
			JSONArray jsonArray = (JSONArray) object;
			for(int i=0; i<jsonArray.size();i++) {
				JSONObject jsonObject = (JSONObject) jsonArray.get(i);
				Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet();
				for(Map.Entry<String, JsonElement> entry : entries) {
					System.out.println(entry.getKey() + " -> "+entry.getValue());
		} catch (ParseException e) {

4)Once you run above you will see following kind of output

firstName -> John
gender -> male
latsName -> Dow
age -> 27

You may also like...