Should computer programming take priority over math in the high school curriculum?

If we take a look at the world as we know it today, we can easily spot that technology has taken over our lives. It is so deeply intertwined with everything we do that it would be difficult and challenging to give up using it at all.

This, along with the popularity of some of the richest people on the planet, has created a collective wish: to try to be like them or even better. More and more children want to be computer scientists, to invent the next Facebook or Microsoft. And a legit question has appeared.

Should computer programming take priority over the math in the high school curriculum? If students want to learn more about computer science, should we make it a priority over other subjects? Should the high school math curriculum be changed? Let’s find out the answer to these questions.

Should computer science be made a priority over math?

The direct and clear answer to this question is no. Even though many students in high school would love to learn more about computer science, coding, and programming, this does not mean that it should be a priority over math.

Math anxiety is a real thing that is more and more present in our schools. And both students and their parents are trying to find solutions to cope with it easily. In this case, learning computer science might seem more attractive. It seems that it can help you build a nice future career, especially as there are a lot of resources you can access. But these subjects complement each other nicely.

Concepts you study in math will be useful in computer science too. Learning computer science without math will make it more difficult to evolve and build a solid knowledge base. Many high school math questions shed more light on some challenging computer science concepts, such as algorithms. No matter if you do online high school math, or you go to classes, what you learn during these hours will be of tremendous help.

However, learning computer science is just as important as learning mathematics. Let’s see why.

Having an Advantage

Considering the fact that technology is so deeply intertwined with our lifestyles, knowing how to use it is always a plus. But anyone knows how to use a smartphone or smartwatch as they are user-friendly. But what happens if you want to go beyond the traditional user interface? What happens if a nice idea strikes you, and you want to try it and see how it works?

Well, for this you need computer science knowledge. Which can be developed and improved during high school, with an equal emphasis on math too. Having at least the basic knowledge to get started in computer science or build your custom app can prove to be an advantage.

Computer Science Can Be Used to Teach Math

The best math apps for high school have a few modules that help you practice the easiest and most difficult math concepts equally. But sometimes, learning math can feel like a burden. As mentioned above, math anxiety is something common, and it can be triggered by a lot of factors. But what is important is that math just builds upon the previous year.

So, if you haven’t understood the math concepts taught earlier, it would be difficult to advance. Well, this is the case for many students. And computer science can be used to teach math. High school students are more attracted by new technologies, platforms, and apps to use and discover. And because computer science relies on math concepts, it can be used to teach math to students too.

Like this, students can understand the connection of math with real life too. A lot of them think that what they learn during math classes will not be useful later in life. Some even ask themselves how integrals, derivatives, or matrices help them. But if you understand that all these complex concepts are present in computer science in one way or another, learning them might be easier.

Final Words

Many students and people fail to understand that math is present in our everyday life. And as computer science is a much more appealing subject, many think about it taking priority over the math in the high school curriculum. Even though this might sound nice, these two subjects complement each other, and they should be given equal priority.

Jackson for Java. Is it more than JSON?

JSON has been a popular data-interchange format for quite some time now. It is not just simple, but also lightweight, and most programmers find it easy to use. However, JSON can be cumbersome to work with when you need more complex functionality.

That’s where Jackson for Java comes in. Jackson is a powerful JSON library that provides a wide range of features that make working with JSON much easier. In this blog post, we will discuss what Jackson for Java is, how it differs from regular JSON, and how you can use it in your own projects. We will also take a look at the pros and cons of using Jackson for Java so that you can decide if it is the right library for you.

What is Jackson for Java, and what are its Features?

Jackson is a Java library that provides a number of features that make working with JSON much easier. Some of the most notable features of Jackson for Java include:

  • The ability to annotate fields so that they are mapped to specific JSON keys: With Jackson, you can annotate fields in your Java objects so that they are mapped to specific keys in the JSON document. This makes it much easier to work with complex JSON documents. For example, if you have a field in your Java object that is mapped to a “name” key in the JSON document, you can access that field using the @JsonProperty("name") annotation.

  • Support for POJOs (Plain Old Java Objects) and JAXB beans (Java Architecture for XML Binding): Jackson supports both POJOs and JAXB beans. This means that you can serialize and deserialize objects without writing any boilerplate code.

  • A wide range of modules that provide additional functionality: Jackson comes with a number of modules that provide additional functionality. These modules include support for XML, YAML, and CSV formats.

In addition to these features, Jackson also has excellent performance thanks to its use of streaming data processing. This means that it can handle large amounts of data with ease.

JSON vs. Jackson for Java – what’s the difference?

The main difference between JSON and Jackson for Java is that Jackson is a library that provides additional functionality on top of JSON. This includes features such as the ability to annotate fields, support for POJOs and JAXB beans, and the ability to serialize and deserialize objects without writing any boilerplate code.

So, if you need additional functionality beyond what JSON provides, then Jackson is the library for you. However, if you only need the basic functionality that JSON provides, then JSON is a better choice.

How to use Jackson for Java in your Project?

If you want to use Jackson for Java in your project, the first step is to add the library to your project dependencies.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

The easiest way to do this is using a dependency management tool such as Maven or Gradle. Once you have added the Jackson library to your project, you can start using it in your code. For example, if you have a field in your Java object that is mapped to a “name” key in the JSON document, you can access that field using the @JsonProperty("name") annotation. Here is an example of how you can convert List object to JSON. Here, we’ll be using the ObjectMapper.writeValueAsString() method.

package net.javaguides.jackson;

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
* Using Jackson API for list serialization and deserialization
* @author ramesh fadatare
*
*/
public class JacksonListToJson {
    public static void main(String[] args) throws JsonProcessingException {

        // Create ObjectMapper object.
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        List < String > progLangs = new ArrayList < > ();
        progLangs.add("C");
        progLangs.add("C++");
        progLangs.add("Java");
        progLangs.add("Java EE");
        progLangs.add("Python");
        progLangs.add("Scala");
        progLangs.add("JavaScript");
        // Serialize Object to JSON.
        String json = mapper.writeValueAsString(progLangs);

        // Print json
        System.out.println(json);
    }
}

You can also use Jackson to serialize and deserialize objects without writing any boilerplate code. This is because Jackson automatically generates the necessary code for you. To do this, you simply need to add the @JsonSerialize and @JsonDeserialize annotations to your Java objects.

If you have some experience on Jackson for Java, you may want to include it in your resume. Now, a resume for a programmer should list programming languages, software, and tools the individual is proficient in. Additionally, project experience and technical skills should be highlighted. A résumé is essentially your career booster so you will need to ensure that it also showcases all your skills and experience. Take time to include every essential detail.

Pros and Cons of Using Jackson for Java

Jackson is a very powerful library that can make working with JSON much easier. There are pros and cons to using Jackson for Java. The main pro is that it’s a very fast and lightweight library, which makes it ideal for large-scale projects. It can also serialize and deserialize Java objects quickly.

However, one potential con is that it can be difficult to reverse certain operations performed by the library, such as converting back from JSON to Java. For example, if you have a Java object with a list of Cat objects, and you want to convert it back to JSON, reversing the process might not be as straightforward as you’d like. In cases like this, you may need to use a different library or write your own code to handle the conversion.

Another potential downside of using Jackson is that because it’s so popular, there may be less flexibility in how you use it. For example, if you want to use Jackson for XML parsing, you may need to use a third-party library such as JAXB.

Overall, Jackson is a very powerful library that can make working with JSON much easier. It has a few potential downsides, but its pros far outweigh its cons.

Comparison of Other Popular JSON Libraries

There are many different JSON libraries available for Java. Some of the most popular include Gson, org.json, and FastJSON. Gson is a library that can be used for converting between Java objects and JSON documents. It can also be used for serializing and deserializing objects. Gson has excellent performance thanks to its use of streaming data processing.

Org.json is a library that provides JSON parsing and generation in Java. It’s simple and easy to use, but it doesn’t provide as much functionality as some other libraries on this list. Here is an example of how to parse JSON string in Java with org.json library.

import org.json.*;

String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++) {
    String post_id = arr.getJSONObject(i).getString("post_id");
    ......
}

See more examples on this page. FastJSON is a high-performance JSON library for Java. It’s simple to use and provides a wide range of features.

Wrapping Up

Overall, Jackson is the best choice for working with JSON in Java, thanks to its excellent performance and wide range of features. However, there are other great options available, so be sure to choose the library that’s right for your project.

Java Project Ideas To Implement While Being in College

According to the Oracle estimations, Java runs on over 15 billion devices around the world. The TIOBE index defines Java as the 3rd most popular programming language. It’s used almost everywhere where coding is required, from mobile games and business apps to automated tests, etc. The biggest companies in the world, like Google, Apple and Android, use Java as it’s a stable language, showing no signs of going anywhere.

Many employees look for experts in Java, so your skills will be in high demand. Java developers make good money, that’s why your job can be really rewarding. What’s more, Java is beginner-friendly. So if you are afraid of complexity, there is no need to worry.

However, learning Java while still at college can be a challenge. Combining different disciplines at the same time usually feels daunting. What to do in this case? You should ask for academic help. For example, you may buy essays online for college or request assistance with your papers at special companies. Also, a good solution would be using automated online tools, such as plagiarism checkers and citation generators. No matter what kind of help you decide to use, you should prioritize things right. If learning Java is the most important thing at college, put the rest aside.

Java projects for beginners

If you are just starting your big journey in the world of Java, you should consider some project ideas listed below.

Airline reservation system

To gain your first hands-on experience, you can try working on the airline reservation system. Include the following elements to your system: e-ticket operations, online transactions, inventory and fares. Your reservation system must contain such features as reservation and cancellation of the tickets, transaction management, routing functions, quick responses to customers and reports on the daily business transactions.

Course management system

Another thing you can design as a beginner is an online management software application for educational institutions. You must include three main elements into your course management system: administrator, student and instructor modules. Administrator module is used to create accounts for students and instructors, make curriculum and manage the employees. Student module is designed for learners who need to view their coursework, get feedback and submit their assignments. Instructor module allows instructors to log in to their accounts in order to check the projects and provide guidance to students.

Data visualization software

One of the key elements of the modern tech industry is data visualization. In this project, you can learn how to deliver insights hidden in the data precisely and effectively. This is a great chance to become better at stimulating the viewer’s engagement. Note that your project must be not only functional, while conveying ideas effectively, but also aesthetically pleasing. Having data visualization projects in your portfolio will make your resume look much more appealing for employers than others.

e-Healthcare management system

If you want to learn how to provide effective solutions for the medical industry, you should try to work on the e-healthcare management system. What are the key features of this software? First of all, it must establish clear communication between doctors and patients. Secondly, it must accurately analyze hospital resources, such as laboratory equipment, administration, medicines and more. One of the main goals of an e-healthcare management system is to eliminate the problems of missing or incorrect data.

Email client software

If you are interested in email marketing, why not use your skills for developing an email system? Design a project for sending and receiving electronic mail, using Java Mail API. For this software you should use SMTP and POP3 protocols that are easy to understand for beginners. Products like this are in high demand nowadays, so you could benefit a lot from having it in your portfolio.

Electricity billing system

Even being a beginner Java developer, you can create an electricity billing system that will calculate the units consumed within a specified timeframe. In accordance with that information, an electricity billing system calculates the cost of those units. To make your software excellent, you should ensure that it features both a high speed and accuracy. It must also allow for seamless data sharing and high-security controls.

Final thoughts

Studying Java coding can be one of the best academic decisions in your life. This programming language is in high demand on the job market, so you should master your skills as soon as possible. Do it with the help of projects for beginners listed above: airline reservation system, course management system, data visualization software, e-healthcare management system, email client software and electricity billing system.

How do I find Java version?

The simplest way to get the Java version is by running the java -version command in your terminal application or Windows command prompt. If Java is installed and available on your path you can get information like below.

java -version                                     
java version "17" 2021-09-14 LTS
Java(TM) SE Runtime Environment (build 17+35-LTS-2724)                       
Java HotSpot(TM) 64-Bit Server VM (build 17+35-LTS-2724, mixed mode, sharing)

Using System Properties

But if you want to get Java version from your Java class or application you can obtain the Java version by calling the System.getProperty() method and provide the property key as argument. Here are some property keys that related to Java version that you can read from the system properties.

package org.kodejava.lang;

public class JavaVersion {
    public static void main(String[] args) {
        String version = System.getProperty("java.version");
        String versionDate = System.getProperty("java.version.date");
        String runtimeVersion = System.getProperty("java.runtime.version");
        String vmVersion = System.getProperty("java.vm.version");
        String classVersion = System.getProperty("java.class.version");
        String specificationVersion = System.getProperty("java.specification.version");
        String vmSpecificationVersion = System.getProperty("java.vm.specification.version");

        System.out.println("java.version: " + version);
        System.out.println("java.version.date: " + versionDate);
        System.out.println("java.runtime.version: " + runtimeVersion);
        System.out.println("java.vm.version: " + vmVersion);
        System.out.println("java.class.version: " + classVersion);
        System.out.println("java.specification.version: " + specificationVersion);
        System.out.println("java.vm.specification.version: " + vmSpecificationVersion);
    }
}

Running the code above give you output like the following:

java.version: 17
java.version.date: 2021-09-14
java.runtime.version: 17+35-LTS-2724
java.vm.version: 17+35-LTS-2724
java.class.version: 61.0
java.specification.version: 17
java.vm.specification.version: 17

Using Runtime.version()

Since JDK 9 we can use Runtime.version() to get Java runtime version. The feature(), interim(), update and patch() methods of the Runtime.Version class are added in JDK 10. These methods is a replacement for the major(), minor() and security() methods of JDK 9.

Below is the code snippet that demonstrate the Runtime.version().

package org.kodejava.lang;

public class RuntimeVersion {
    public static void main(String[] args) {
        System.out.println("Version: " + Runtime.version());
        System.out.println("Feature: " + Runtime.version().feature());
        System.out.println("Interim: " + Runtime.version().interim());
        System.out.println("Update: " + Runtime.version().update());
        System.out.println("Patch: " + Runtime.version().patch());
        System.out.println("Pre: " + Runtime.version().pre().orElse(""));
        System.out.println("Build: " + Runtime.version().build().orElse(null));
        System.out.println("Optional: " + Runtime.version().optional().orElse(""));
    }
}

Running the code snippet above produce the following output:

Version: 17+35-LTS-2724
Feature: 17
Interim: 0
Update: 0
Patch: 0
Pre: 
Build: 35
Optional: LTS-2724

Here are the summary of outputs running the above code using some JDKs installed on my machine.

Version Feature Interim Update Patch Pre Build Optional
10.0.2+13 10 0 2 0 13
11.0.6+8-LTS 11 0 6 0 8 LTS
12.0.2+10 12 0 2 0 10
13.0.2+8 13 0 2 0 8
14+36-1461 14 0 0 0 36 1461
15.0.2+7-27 15 0 2 0 7 27
17+35-LTS-2724 17 0 0 0 35 LTS-2724

Java and Blockchain – a match made in heaven

Java is the foundation of many products. It is no coincidence that this amazing programming language affects the cryptocurrency world (including Bitcoin). But what makes people buy USDT and how blockchain could help our world modernize for good? Let’s find out in this article.

What is blockchain?

Blockchain is an open, distributed ledger that can record transactions between two parties efficiently, in a verifiable and permanent way. Blockchain databases aren’t stored in any single location, meaning the records it keeps are truly public and easily verifiable. The data stored isn’t controlled by any one entity, meaning the system isn’t subject to the whims of any government, corporation or malicious third party.

Benefits of using blockchain

Obviously, what’s the point of discussing the topic, if we will skip the benefits of blockchain?

Decentralized

Blockchain is decentralized meaning it doesn’t have a governing body. No one can single-handedly decide to change how the blockchain project will continue to work, unless they own 51% of the blockchain. Since that is nearly impossible, blockchains are owned by nobody, unless it’s a private blockchain.

Immutable

Immutability is what makes the blockchain so revolutionary. Unlike traditional database records, which are prone to manipulation and deletion due to centralization, blockchain records are unalterable and permanent. Every blockchain transaction is time-stamped and date-stamped, giving it a timestamp of its very occurrence, allowing users to trace the origin and evolution of any data on the chain. It, therefore, enables users to verify information over time, ensuring reliability. If you decide to buy a car with Bitcoin, nobody could ever change that.

Secure

Though it was first used to track bitcoin transactions, blockchain technology has attracted the interest of a variety of industries. Major companies like IBM, Walmart and Maersk are using blockchain to run complex global supply chains with less friction, prevent fraud and reduce waste. Beyond bringing accountability to systems where trust has been an issue, the technology can also help ensure consumer privacy.

Coding skills – not much needed

Since we care about coding, we cannot move on without giving some helpful tips on how to use Java for blockchain.

Let’s implement a block

public class Block {
    private String hash;
    private String previousHash;
    private String data;
    private long timeStamp;
    private int nonce;

    public Block(String data, String previousHash, long timeStamp) {
        this.data = data;
        this.previousHash = previousHash;
        this.timeStamp = timeStamp;
        this.hash = calculateBlockHash();
    }

    // standard getters and setters
}

Then, we need to work on the hashing. Bear in mind it is very sensitive. Any data altercation could be detrimental.

public String calculateBlockHash() {
    String dataToHash = previousHash
            + Long.toString(timeStamp)
            + Integer.toString(nonce)
            + data;
    MessageDigest digest = null;
    byte[] bytes = null;
    try {
        digest = MessageDigest.getInstance("SHA-256");
        bytes = digest.digest(dataToHash.getBytes(UTF_8));
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
        logger.log(Level.SEVERE, ex.getMessage());
    }
    StringBuffer buffer = new StringBuffer();
    for (byte b : bytes) {
        buffer.append(String.format("%02x", b));
    }
    return buffer.toString();
}

From what we see, we get a case of SHA-256 (cryptography), and then generate a hash value from our input data. The byte array is a very crucial part here – it is the hash value that we transform later into a hex string (usually, a 32-digit number).

But how to mine a block?

public String mineBlock(int prefix) {
    String prefixString = new String(new char[prefix]).replace('\0', '0');
    while (!hash.substring(0, prefix).equals(prefixString)) {
        nonce++;
        hash = calculateBlockHash();
    }
    return hash;
}

We start by looking for the solution. If we don’t manage to do so, we increment the nonce and calculate our hash in a loop until we finally make it. I have to tell you – it might take a long time before you hit the jackpot.

Blockchain verification

How to verify the blockchain? After all, there are plenty of fake attempts, so we need to see if our attempt is valid.

public void givenBlockchain_whenValidated_thenSuccess() {
    boolean flag = true;
    for (int i = 0; i < blockchain.size(); i++) {
        String previousHash = i==0 ? "0" : blockchain.get(i - 1).getHash();
        flag = blockchain.get(i).getHash().equals(blockchain.get(i).calculateBlockHash())
                && previousHash.equals(blockchain.get(i).getPreviousHash())
                && blockchain.get(i).getHash().substring(0, prefix).equals(prefixString);
        if (!flag) break;
    }
    assertTrue(flag);
}

Summary

Java and blockchain are made to work together. However, it is not easy to mine blockchain. That is why, we advise you to enter pools, in order to share prizes with others but ensure you are on the winning side.

How do I convert CSV to JSON string using Jackson?

In the following code snippet we will convert CSV into JSON string using Jackson JSON library. A comma-separated values is a delimited text, it uses comma to separate values. It starts with header on the first line, that will be the JSON key. Each subsequence lines is the data of the csv, which also contains several values separated by comma.

Let’s see the code how to do this in Jackson.

package org.kodejava.jackson;

import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class CsvToJson {
    public static void main(String[] args) {
        // Comma delimited text created using text blocks
        String countries = """
                ISO, CODE, NAME\s
                CZE, CZ, Czech Republic\s
                DNK, DK, Denmark\s
                DJI, DJ, Djibouti\s
                DMA, DM, Dominica\s
                ECU, EC, Ecuador
                """;

        CsvSchema csvSchema = CsvSchema.emptySchema().withHeader();
        CsvMapper csvMapper = new CsvMapper();

        try {
            MappingIterator<Map<?, ?>> mappingIterator = csvMapper.reader()
                    .forType(Map.class)
                    .with(csvSchema)
                    .readValues(countries);
            List<Map<?, ?>> list = mappingIterator.readAll();

            ObjectMapper objectMapper = new ObjectMapper();
            String jsonPretty = objectMapper.writerWithDefaultPrettyPrinter()
                    .writeValueAsString(list);
            System.out.println(jsonPretty);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Here are the explanation of the code above:

  • Define a csv string, in this case we have a list of countries.
  • Create an empty schema of CsvSchema to process csv with header line.
  • Create an instance of CsvMapper, a specialized type of ObjectMapper.
  • Read and parse csv values into List<Map<?, ?>>.
  • We use the ObjectMapper create a pretty-printed JSON from the list object.

Running the code produces the following output:

[ {
  "ISO" : "CZE",
  "CODE" : " CZ",
  "NAME" : " Czech Republic "
}, {
  "ISO" : "DNK",
  "CODE" : " DK",
  "NAME" : " Denmark "
}, {
  "ISO" : "DJI",
  "CODE" : " DJ",
  "NAME" : " Djibouti "
}, {
  "ISO" : "DMA",
  "CODE" : " DM",
  "NAME" : " Dominica "
}, {
  "ISO" : "ECU",
  "CODE" : " EC",
  "NAME" : " Ecuador"
} ]

Maven Dependencies

<dependencies>
    <!-- https://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-core/2.13.2/jackson-core-2.13.2.jar -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.13.2</version>
    </dependency>
    <!-- https://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-annotations/2.13.2/jackson-annotations-2.13.2.jar -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.13.2</version>
    </dependency>
    <!-- https://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-databind/2.13.2/jackson-databind-2.13.2.jar -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.13.2</version>
    </dependency>
    <!-- https://search.maven.org/remotecontent?filepath=com/fasterxml/jackson/dataformat/jackson-dataformat-csv/2.13.2/jackson-dataformat-csv-2.13.2.jar -->
    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-csv</artifactId>
        <version>2.13.2</version>
    </dependency>    
</dependencies>

Maven Central Maven Central Maven Central Maven Central

How do I convert CSV file to or from JSON file?

In the following code snippet you will see how to convert a CSV file into JSON file and vice versa. We use the JSON-Java library CDL class to convert between CSV and JSON format. The CDL class provide the toJSONArray(String) and toString(JSONArray) methods that allows us to do the conversion between data format.

In the CSV file, the first line in the file will be use as the keys to the generated JSON string. On the other way around, the JSON string keys will be written on the first line of the CSV file as the column header.

Convert CSV file to JSON file.

package org.kodejava.json;

import org.json.CDL;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import java.util.stream.Collectors;

public class CsvFileToJsonFile {
    public static void main(String[] args) {
        // Read csv data file and store it in a string
        InputStream is = CsvFileToJsonFile.class.getResourceAsStream("/data.csv");
        String csv = new BufferedReader(
                new InputStreamReader(Objects.requireNonNull(is), StandardCharsets.UTF_8))
                .lines()
                .collect(Collectors.joining("\n"));

        try {
            // Convert csv text to JSON string, and save it 
            // to a data.json file.
            String json = CDL.toJSONArray(csv).toString(2);
            Files.write(Path.of("data.json"), json.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

What we do in the snippet above:

  • Get cvs data as InputStream from the resources directory.
  • We use the BufferedReader and InputStreamReader to iterate and read the InputStream and return it as a string.
  • Convert the csv string into JSON string using CDL.toJSONArray().
  • We can pretty-printed the JSON string by specifying an indentFactor to the toString() method of the JSONArray object.
  • Write the JSON string to a file.

Here is the data.csv file example.

id,first_name,last_name,email,gender,ip_address
1,Abe,Foord,afoord0@harvard.edu,Female,81.38.18.88
2,Editha,Castagnaro,ecastagnaro1@nih.gov,Genderqueer,181.63.39.199
3,Tildie,Furminger,tfurminger2@hud.gov,Male,0.199.18.3

Convert JSON file to CSV file.

package org.kodejava.json;

import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONTokener;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;

public class JsonFileToCsvFile {
    public static void main(String[] args) {
        // Get data.json resource as InputStream, create JSONTokener
        // and convert the tokener into JSONArray object.
        InputStream is = JsonFileToCsvFile.class.getResourceAsStream("/data.json");
        JSONTokener tokener = new JSONTokener(Objects.requireNonNull(is));
        JSONArray jsonArray = new JSONArray(tokener);

        try {
            // Convert JSONArray into csv and save to file
            String csv = CDL.toString(jsonArray);
            Files.write(Path.of("data.csv"), csv.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

What we do in the code snippet above:

  • Get data.json from the resources directory as InputStream.
  • Create a JSONTokener and provide the InputStream as argument to its constructor.
  • Create a JSONArray and pass the JSONTokener object as the constructor argument.
  • Using CDL.toString() we convert the JSONArray object to csv text.
  • Finally, save the csv into file using Files.write().

And here is the data.json JSON file example.

[
  {
    "id": "1",
    "first_name": "Abe",
    "last_name": "Foord",
    "email": "afoord0@harvard.edu",
    "gender": "Female",
    "ip_address": "81.38.18.88"
  },
  {
    "id": "2",
    "first_name": "Editha",
    "last_name": "Castagnaro",
    "email": "ecastagnaro1@nih.gov",
    "gender": "Genderqueer",
    "ip_address": "181.63.39.199"
  },
  {
    "id": "3",
    "first_name": "Tildie",
    "last_name": "Furminger",
    "email": "tfurminger2@hud.gov",
    "gender": "Male",
    "ip_address": "0.199.18.3"
  }
]

Maven Dependencies

<dependencies>
    <!-- https://search.maven.org/remotecontent?filepath=org/json/json/20211205/json-20211205.jar -->
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20211205</version>
        <type>bundle</type>
    </dependency>
</dependencies>

Maven Central

How do I convert CSV into JSON string using JSON-Java?

In this example we convert CSV or CDL into JSON string. We are going to use the JSON-Java CDL (Comma Delimited Text) class. This class provides static methods that will convert a CSV into JSONArray or to convert a JSONArray into comma separated values.

Here are what we do in the code snippet below:

  • Create a comma delimited text. The first line is the headers, this will be the keys in our JSON string. The couples lines is the values. We use the Java text blocks feature to define the string.
  • Create JSONArray object by calling CDL.toJSONArray() static method as pass the comma delimited string as argument.
  • Next we create a JSONArray object, but we separate the header and the body. We do this by calling the CDL.toJSONArray() and provides headers and countries as arguments.
  • Last, we call the CDL.toString() method with JSONArray as argument to convert it to comma delimited text.

Let’s see the code in action.

package org.kodejava.json;

import org.json.CDL;
import org.json.JSONArray;

public class CsvToJson {
    public static void main(String[] args) {
        // Comma delimited text created using text blocks
        String countries = """
                ISO, CODE, NAME\s
                CZE, CZ, CZECH REPUBLIC\s
                DNK, DK, DENMARK\s
                DJI, DJ, DJIBOUTI\s
                DMA, DM, DOMINICA\s
                ECU, EC, ECUADOR
                """;

        // Convert comma delimited text into JSONArray object.
        JSONArray jsonCountries = CDL.toJSONArray(countries);
        System.out.println(jsonCountries.toString(2));

        // Using a separate header and values to create JSONArray
        // from a comma delimited text
        JSONArray header = new JSONArray();
        header.put("ISO");
        header.put("CODE");
        header.put("NAME");

        countries = """
                CZE, CZ, CZECH REPUBLIC\s
                DNK, DK, DENMARK\s
                DJI, DJ, DJIBOUTI\s
                DMA, DM, DOMINICA\s
                ECU, EC, ECUADOR
                """;

        jsonCountries = CDL.toJSONArray(header, countries);
        System.out.println(jsonCountries.toString(2));

        // Convert back from JSONArray to comma delimeted text
        countries = CDL.toString(jsonCountries);
        System.out.println(countries);
    }
}

Running the code produces the following results.

To JSON string:

[
  {
    "ISO": "CZE",
    "CODE": "CZ",
    "NAME": "CZECH REPUBLIC"
  },
  {
    "ISO": "DNK",
    "CODE": "DK",
    "NAME": "DENMARK"
  },
  {
    "ISO": "DJI",
    "CODE": "DJ",
    "NAME": "DJIBOUTI"
  },
  {
    "ISO": "DMA",
    "CODE": "DM",
    "NAME": "DOMINICA"
  },
  {
    "ISO": "ECU",
    "CODE": "EC",
    "NAME": "ECUADOR"
  }
]

Back to CSV

ISO,CODE,NAME
CZE,CZ,CZECH REPUBLIC
DNK,DK,DENMARK
DJI,DJ,DJIBOUTI
DMA,DM,DOMINICA
ECU,EC,ECUADOR

Maven Dependencies

<dependencies>
    <!-- https://search.maven.org/remotecontent?filepath=org/json/json/20211205/json-20211205.jar -->
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20211205</version>
        <type>bundle</type>
    </dependency>
</dependencies>

Maven Central

How do I pretty-print JSON string in Google Gson?

In the following example you’ll see how to format JSON string using the Google Gson library. Here are the steps:

  • We create a Map.
  • Put a couple key-value pairs to it. We put a string, a LocalDate object and an array of String[].
  • Create a Gson object using the GsonBuilder. This allows us to configure the Gson object.
  • We use the setPrettyPrinting() to configure Gson to output pretty print.
  • The registerTypeAdapter() allows us to register custom serializer, in this case we use it to serialize LocalDate object.

Here is our code snippet:

package org.kodejava.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class GsonPrettyPrint {
    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "Duke");
        map.put("address", "Menlo Park");
        map.put("dateOfBirth", LocalDate.of(2000, Month.FEBRUARY, 1));
        map.put("languages", new String[]{"Java", "Kotlin", "JavaScript"});

        Gson gson = new GsonBuilder()
                .setPrettyPrinting()
                .registerTypeAdapter(LocalDate.class, new LocaleDateAdapter())
                .create();
        String json = gson.toJson(map);
        System.out.println(json);
    }

    static class LocaleDateAdapter implements JsonSerializer<LocalDate> {
        @Override
        public JsonElement serialize(LocalDate date, Type type, JsonSerializationContext jsonSerializationContext) {
            return new JsonPrimitive(date.format(DateTimeFormatter.ISO_DATE));
        }
    }
}

Running this code produces the following result:

{
  "address": "Menlo Park",
  "languages": [
    "Java",
    "Kotlin",
    "JavaScript"
  ],
  "name": "Duke",
  "dateOfBirth": "2000-02-01"
}

Maven Dependencies

<!-- http://repo1.maven.org/maven2/com/google/code/gson/gson/2.8.9/gson-2.8.9.jar -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>

Maven Central

How do I pretty print JSON string in JSON-Java?

In JSON-Java we can make a pretty-printed JSON string by specifying an indentFactor to the JSONObject‘s toString() method. The indent factor is the number of spaces to add to each level of indentation.

If indentFactor > 0 and the JSONObject has only one key, the JSON string will be printed a single line, and if the JSONObject has 2 or more keys, the JSON string will be printed in multiple lines.

Let’s create a pretty-printed JSONObject text using the code below.

package org.kodejava.json;

import org.json.JSONArray;
import org.json.JSONObject;

public class PrettyPrintJSON {
    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", 1L);
        jsonObject.put("name", "Alice");
        jsonObject.put("age", 20);
        JSONArray courses = new JSONArray(
                new String[]{"Engineering", "Finance"});
        jsonObject.put("courses", courses);

        // Default print without indent factor
        System.out.println(jsonObject);

        // Pretty print with 2 indent factor
        System.out.println(jsonObject.toString(2));
    }
}

Running this code produces the following output:

{"courses":["Engineering","Finance"],"name":"Alice","id":1,"age":20}
{
  "courses": [
    "Engineering",
    "Finance"
  ],
  "name": "Alice",
  "id": 1,
  "age": 20
}

Maven Dependencies

<dependencies>
    <!-- https://search.maven.org/remotecontent?filepath=org/json/json/20211205/json-20211205.jar -->
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20211205</version>
        <type>bundle</type>
    </dependency>
</dependencies>

Maven Central