How to change json property name dynamically in java

In Java, you can change the property name dynamically in a JSON object by using the `JSONObject` class provided by the `org.json` library. Here’s how you can do it:


import org.json.JSONObject;

public static void main(String[] args) {
    // Create a JSON object
    JSONObject jsonObject = new JSONObject();
  
    // Add properties to the JSON object
    jsonObject.put("name", "John");
    jsonObject.put("age", 25);
  
    // Print the original JSON object
    System.out.println("Original JSON Object:");
    System.out.println(jsonObject.toString());
  
    // Rename the property dynamically
    String oldPropertyName = "name";
    String newPropertyName = "fullName";
  
    Object propertyValue = jsonObject.remove(oldPropertyName);
    jsonObject.put(newPropertyName, propertyValue);
  
    // Print the updated JSON object
    System.out.println("\nUpdated JSON Object:");
    System.out.println(jsonObject.toString());
}
    

In this example, we first create a `JSONObject` and add two properties: “name” and “age”. Then, we print the original JSON object.

To dynamically change the property name, we specify the old property name and the new property name. We use the `remove()` method to remove the property with the old name from the JSON object and store its value. Then, we use the `put()` method to add the value with the new property name.

Finally, we print the updated JSON object with the new property name.

Leave a comment