How to Write JSON File Data Using Java? – Devstringx

Back to Blog
Feature image for write JSON data blog

How to Write JSON File Data Using Java? – Devstringx

What Is JSON?

JSON stands for JavaScript Object Notation and it is lightweight and language-independent. An (API) application program interface (a set of rules that dictate how two machines talk to each other) is the most preferred JSON format data.

It is a hierarchy format of data and there are many ways to read write and update this format data.

Important Keys Points to Write JSON Data

Before start writing JSON data using JAVA we should know some important keys points that are mentioned below:-

  • JsonPath

It uses to extract data from a JSON document .it follows the Groovy Path syntax when getting an object from the documents. The package name is io.restassured.path.json.JsonPath.

  • ObjectMapper

is a class that provides the functionality for reading and Writing the Json for a better conversation. The specific package used for Object Mapper is org.codehaus.jackson.map.ObjectMapper.

  • JsonParser

is used to read–only access to JSON data in a streaming way .this is an effective way of reading the JSON data. References ->JsonParser

  • ObjectWriter

is a method that is used to serialize the Java value as a byte array in String format: References -> ObjectWriter. The Package used for ObjectWriter is com. faster XML.jackson. data-bind.ObjectWriter

Code to Write Action into JSON

We have to use the below code in Java for updating or writing actions into the above JSON

import java.io.FileReader;

import java.io.IOException;

import java.nio.file.Paths;




import org.codehaus.jackson.impl.DefaultPrettyPrinter;

import org.codehaus.jackson.map.ObjectMapper;

import org.codehaus.jackson.map.ObjectWriter;

import org.json.simple.JSONObject;

import org.json.simple.parser.JSONParser;
class JsonExample {

            public static void main(String args[]) {

            ObjectMapper mapper = new ObjectMapper();

            String jsonPath = "C:\\Users\\ABC\\Documents\\API_testing\\jsonex\\sample.json";

            try {

                        JSONParser jsonParser = new JSONParser();

                        JSONObject obj = (JSONObject) jsonParser.parse(new FileReader(jsonPath));

                        obj.put("lastName", "Yadav");

                        ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());

                        writer.writeValue(Paths.get(jsonPath).toFile(), obj);

                        System.out.println("Name updated .........");

                        } catch (Exception e) {

                        e.printStackTrace();

                        }

            }

Example to Update JSON Data

JSON Data Updated from a particular path location in Java Example

Example: C:\Users\ABC\Documents\API_testing\jsonex\\sample.json

{

  "lastName" : "Yadav",

  "firstName": "John",

  "address": {

    "streetAddress": "21 2nd Street",

    "city": "New York",

    "postalCode" : 10021,

    "state": "NY"

  },

  "age": 25,

  "phoneNumbers" : [ {

    "number": "212 555-1234",

    "type": "home"

  }, {

    "number": "212 555-1234",

    "type": "fax"

  } ]

}

Important Dependencies

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>DemoProject</groupId>

  <artifactId>DemoProject</artifactId>

  <version>0.0.1-SNAPSHOT</version>

  <build>

    <sourceDirectory>src</sourceDirectory>

    <plugins>

      <plugin>

        <artifactId>maven-compiler-plugin</artifactId>

        <version>3.8.1</version>

        <configuration>

          <release>14</release>

        </configuration>

      </plugin>

    </plugins>

  </build>

  <dependencies>

  <!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured --> 

<dependency>

    <groupId>io.rest-assured</groupId>

    <artifactId>rest-assured</artifactId>

    <version>4.4.0</version>

</dependency>

<dependency>

    <groupId>com.googlecode.json-simple</groupId>

    <artifactId>json-simple</artifactId>

    <version>1.1.1</version>

</dependency>

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->

<dependency>

    <groupId>com.fasterxml.jackson.core</groupId>

    <artifactId>jackson-core</artifactId>

    <version>2.15.0</version>

</dependency>

<dependency>

    <groupId>org.codehaus.jackson</groupId>

    <artifactId>jackson-mapper-asl</artifactId>

    <version>1.9.2</version>

</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->

<dependency>

    <groupId>org.testng</groupId>

    <artifactId>testng</artifactId>

    <version>7.4.0</version>

</dependency>

<dependency>

    <groupId>com.jayway.jsonpath</groupId>

    <artifactId>json-path</artifactId>

    <version>2.0.0</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.hamcrest/hamcrest -->

<dependency>

    <groupId>org.hamcrest</groupId>

    <artifactId>hamcrest</artifactId>

    <version>2.2</version>

</dependency>

  </dependencies>

</project>

 

 

Share this post

Back to Blog