Parse String to JSON in Java
In this tutorial, we will learn how to parse string to JSON using different ways in Java..
JSON
stands for Java Script Object Notation, most commonly format used to store an data. A JSON object can be easily converted to a string and vice-versa.
1. Using org.json
Also called as JSON-Java library, provides the method to convert the String to JSON
and JSON
to String. Click for Maven Dependencies
import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; public class JsonParser { public static void main(String[] args) { try { String jsonStr = "{\"Name\": \"Potter\", \"University\": \"Hogwards\"}"; JSONParser jsonParser = new JSONParser(); //convert to json JSONObject jsonObj =(JSONObject) jsonParser.parse(jsonStr); System.out.println(jsonObj); }catch (Exception e) { e.printStackTrace(); } } }
Output
{"University":"Hogwards","Name":"Potter"}
2. Using Jackson Library
Jackson is a popular library for parsing JSON
. Below code snippet will show you how to parsing with Jackson class. Maven Dependencies to use the libraries.
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; class StringToJsonObject { public static void main(String[] args) throws IOException { String jsonStr = "{\"name\": \"Severus\", \"age\": \"40\"}"; // create object mapper ObjectMapper mapper = new ObjectMapper(); // convert to json object JsonNode jsonNode = mapper.readTree(jsonStr); System.out.println(jsonNode.toString()); // get value for a key System.out.println("Name: " + jsonNode.get("name").asText()); } }
Output
{"name":"i30″,"brand":"Hyundai"} Name: Hyundai
3. Using Gson
Gson is a google library used to convert the String to JSON and vice-versa. Dependencies for Maven.
import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class ParseJson { static String jsonStr = "{\"name\": \"Harry\", \"age\": \"12\"}"; public static void main(String[] args) { // Method 1: parsing into a JSON element JsonObject jsonObject = new JsonParser().parse(jsonStr).getAsJsonObject(); System.out.println("parsing into a JSON element::::" + jsonObject); // Method 2: parsing into a Java Object JSON user = new Gson().fromJson(jsonStr, JSON.class); System.out.println("parsing into a Java Object:: Name: " + user.name); System.out.println("parsing into a Java Object:: Age : " + user.age); } }
Output
parsing into a JSON element::::{"name":"Harry","age":"12"} parsing into a Java Object:: Name: Harry parsing into a Java Object:: Age : 12
Hope this post find you needs. Have a great day 🙂