Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaJava Program to Convert Byte Array to JSON

Java Program to Convert Byte Array to JSON

JSON is nothing but Javascript Object Notation. It is a text format to store the data as well as transport the data. Usually, it will be denoted in String value pairs. It is language-independent and can run anywhere. JSON notation contains the below basic elements. Hence the framed byte array (from any source it might have converted (i.e. via static text/Rest API output), it should support the pattern of parsing properly.

Objects Objects begin with ‘{‘(open) and end with ‘}’ (close) curly braces.
Object Members Members are comma-separated and they consist of strings and values.
Arrays Arrays begin with ‘[‘(open) and end with ‘]’ (end) braces and it is almost similar to the Array data structure. In the JSON array, it will be a collection of different values as JSON strings
Values A value can be a string and even it can have a JSONArray or any object or simply constants.
Strings

Strings are surrounded by double quotes(“”) and followed by a Unicode colon (:). There can be several members and each is separated by commas(,).

Values are also separated by commas(,) and include the following. true/false/null/character or common backslash escapes.

Any string can be changed to a byte array and any byte array can be converted to a String easily via the below ways. Assume the String that we are going to take is of the pattern with the above basic elements. Because nowadays any REST service is producing the output in the format of JSON. If the pattern is of that supported structure, we can easily parse it using JSONParser. The below sample set of programs can be used to produce the neat JSONArray Output.

Example 1

Java




import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import java.nio.charset.StandardCharsets;
  
public class Example1 {
    public static void main(String[] args)
    {
        String geekPortalUserDetails
            = "[{\"firstName\":\"GeekA\",\"Posts\":\"100\"},
        {
            \"firstName\":\"GeekB\",\"Posts\":\"150\"},
            {
                \"firstName\":\"GeekC\",\"Posts\":\"50\"}]";
  
                // string to byte[]
                byte[] userDetailsBytes
                    = geekPortalUserDetails.getBytes(
                        StandardCharsets.UTF_8);
  
                // converting the bytes to String
                String userDetailsBytesToStrings
                    = new String(userDetailsBytes,
                                 StandardCharsets.UTF_8);
                JsonParser jsonParser = new JsonParser();
  
                // As the byte array details contains
                // JSONArray elements, we need to parse the
                // output in the form of JsonArray
                JsonArray jsonArrayOutput
                    = (JsonArray)jsonParser.parse(
                        userDetailsBytesToStrings);
                System.out.println("Output : "
                                   + jsonArrayOutput);
            }
        }


The output of the program:

output

 

We can beautify and see the output as follows. Output is in the format of JSON Array

 

The main important thing in converting byte array to JSON is that the byte array should be of the pattern to get parsed using JsonParser. Now let us see an example for a JsonObject 

Example 2

Java




import com.google.gson.*;
import java.nio.charset.StandardCharsets;
  
public class Example2 {
    public static void main(String[] args)
    {
  
        String geekPortalUserDetail
            = "{\"firstName\": \"GeekA\",\"last_name\": \"GeekA\", \"email_address\": \"geeka@gfg.com\"}";
  
        // string to byte[]
        byte[] userDetailsBytes
            = geekPortalUserDetail.getBytes(
                StandardCharsets.UTF_8);
  
        // converting the bytes to String
        String userDetailsBytesToStrings = new String(
            userDetailsBytes, StandardCharsets.UTF_8);
        JsonParser jsonParser = new JsonParser();
  
        // As the output is of the pattern of JsonObject, it
        // has to be converted in this way
        JsonObject jsonObjectOutput
            = (JsonObject)jsonParser.parse(
                userDetailsBytesToStrings);
        System.out.println("Output : " + jsonObjectOutput);
    }
}


Output:

 

We can beautify the same and check

 

Several REST APIs like https://api.exchangerate-api.com/v4/latest/USD produces the response either as JSONObject/JSONArray.

Example:

 

We can keep these data as a byte array in the database and when needed, we can get it back in JSON format.

Reasons:

Few REST APIs are free. Many are paid and it also differs upon hitting count of api. To avoid that, instead of hitting the URL several times, get the response from REST API and store the data in the database as a byte array (because the response will be huge and it may contain photos/videos, etc.,) too. When we need to show the data, we can get the byte array data from DB and parse it like the above sample programs and get either as JSONArray/JSONObject.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments