1. Introduction
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. In Java, converting a String to JSON can be accomplished using libraries such as org.json or Gson. In this example, we’ll use the org.json library. If you don’t have it in your project, you can add it via Maven or Gradle.
2. Program Steps
1. Add the dependency for the org.json library to your project.
2. Create a valid JSON formatted String.
3. Use the JSONObject class from the org.json library to convert the String to a JSON object.
4. Print the JSON object to the console.
3. Code Program
// Step 1: Importing necessary classes
import org.json.JSONObject;
public class StringToJson {
public static void main(String[] args) {
// Step 2: Creating a valid JSON formatted String
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
// Step 3: Converting String to JSON object using JSONObject
JSONObject jsonObj = new JSONObject(jsonString);
// Step 4: Printing the JSON object to the console
System.out.println(jsonObj);
}
}
Output:
{"name":"John","age":30,"city":"New York"}
4. Step By Step Explanation
– Step 1: The necessary class, JSONObject, from the org.json library is imported. This library needs to be added as a dependency to your project.
– Step 2: A String jsonString representing a JSON object is created. It includes name, age, and city as attributes.
– Step 3: A new JSONObject is instantiated using jsonString, converting the String to a JSON object.
– Step 4: The resulting JSONObject is printed to the console, showcasing the successful conversion of the String to a JSON object.
Make sure that the input String is a valid JSON formatted String to avoid JSONException during the conversion.