Convert JSON to Java Object

Convert JSON to Java Object

Here’s an example on how you can convert json to java object. We start first by converting to simple POJO then we’ll also show you how you can do the same for Collections Object.

Add Jackson Dependency

Add the dependency for JSON.


    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    2.7.4


    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    2.7.4

Converting JSON to simple POJO

For example, we have this JSON:

{  
   "id":"60"
   "codeId":"1",
   "codeName":"IT",
   "deleteFlag":0,
   "sort":"1",
}

and we need this JSON to be converted to MstCode object:

public class MstCode {

    private int id;
    private int codeId;
    private String codeName;
    private int deleteFlag;
    private int sort;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getCodeId() {
        return codeId;
    }

    public void setCodeId(int codeId) {
        this.codeId = codeId;
    }

    public String getCodeName() {
        return codeName;
    }

    public void setCodeName(String codeName) {
        this.codeName = codeName;
    }

    public int getDeleteFlag() {
        return deleteFlag;
    }

    public void setDeleteFlag(int deleteFlag) {
        this.deleteFlag = deleteFlag;
    }

    public int getSort() {
        return sort;
    }

    public void setSort(int sort) {
        this.sort = sort;
    }
}

In order for us to convert json to java object, we will use jackson ObjectMapper class.

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JsonConverter {

    public static void main(String[] args) {
        String json = "{\"deleteFlag\":0,\"codeId\":\"1\",\"codeName\":\"IT\",\"sort\":\"1\",\"id\":\"60\"}";
        ObjectMapper mapper = new ObjectMapper();
        try {
            MstCode mstCode = mapper.readValue(json, MstCode.class);
            System.out.print(mstCode.getCodeName());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This produces the below output:

IT

Converting JSON to List of Objects

Now that we have learned how to convert json to POJO, we also should now how we can convert a json which consist of array of json to java.util.List.
For example, consider the below JSON:

[  
   {  
      "deleteFlag":0,
      "codeId":"1",
      "codeName":"IT",
      "sort":"1",
      "id":"60"
   },
   {  
      "deleteFlag":0,
      "codeId":"2",
      "codeName":"Accounting",
      "sort":"2",
      "id":"61"
   },
   {  
      "deleteFlag":0,
      "codeId":"3",
      "codeName":"Support",
      "sort":"3",
      "id":"62"
   }
]


The above json consist of three json which has named IT, Accounting, and Support. To be able to parsed this to java List, we’ll also use the same method but we will changed the second argument.

import com.fasterxml.jackson.databind.ObjectMapper;

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

public class JsonConverter {

    public static void main(String[] args) {
        String json = "[{\"deleteFlag\":0,\"codeId\":\"1\",\"codeName\":\"IT\",\"sort\":\"1\",\"id\":\"60\"},{\"deleteFlag\":0,\"codeId\":\"2\",\"codeName\":\"Accounting\",\"sort\":\"2\",\"id\":\"61\"},{\"deleteFlag\":0,\"codeId\":\"3\",\"codeName\":\"Support\",\"sort\":\"3\",\"id\":\"62\"}]";
        ObjectMapper mapper = new ObjectMapper();
        try {
            List<MstCode> mstCodes = mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, MstCode.class));
            System.out.println(mstCodes.size());
            System.out.println(mstCodes.get(0).getCodeName());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

To convert json to List of object, we will construct the collection type:

mapper.getTypeFactory().constructCollectionType(List.class, MstCode.class)

where List.class is the Collection class and MstCode.class is the class of object that your list will be holding.
Running the above code will result to the following:

3
IT

Create CSV File in Java

How to create CSV File in Java

This example will show you how you can create csv file in java using OpenCSV dependency.
If you’re using maven, add the opencsv dependency in your pom.xml


    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    3.7

or download the jar file in maven central or here

Next, use CSVWriter class to create your csv file:

import com.opencsv.CSVWriter;

import java.io.FileWriter;
import java.io.IOException;

public class CSVExample {

    public static void main(String[] args) throws IOException {
        CSVWriter csvWriter = new CSVWriter(new FileWriter("example.csv"));
        csvWriter.writeNext(new String[]{"1", "jan", "Male", "20"});
        csvWriter.writeNext(new String[]{"2", "con", "Male", "24"});
        csvWriter.writeNext(new String[]{"3", "jane", "Female", "18"});
        csvWriter.writeNext(new String[]{"4", "ryo", "Male", "28"});

        csvWriter.close();
    }
}

This will create a file with name example.csv in your project root path. If opened in notepad, this will result to the following contents:

"1","jan","Male","20"
"2","con","Male","24"
"3","jane","Female","18"
"4","ryo","Male","28"

If your data is in List<String[]> collection object, you can just use the method CSVWriter#writeAll method. Here is an example of passing List object to CSVWriter:

import com.opencsv.CSVWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class CSVExample {

    public static void main(String[] args) throws IOException {
        CSVWriter csvWriter = new CSVWriter(new FileWriter("example.csv"));

        List<String[]> rows = new LinkedList<String[]>();
        rows.add(new String[]{"1", "jan", "Male", "20"});
        rows.add(new String[]{"2", "con", "Male", "24"});
        rows.add(new String[]{"3", "jane", "Female", "18"});
        rows.add(new String[]{"4", "ryo", "Male", "28"});
        csvWriter.writeAll(rows);

        csvWriter.close();
    }
}

Take note that we have used LinkedList as the implementation of the list to preserved the insertion order. The above code when run will result to the same output. Also, by default, the csv values are enclosed by double quotations(“”). If you don’t want to add quotes, you can add a second argument false to the CSVWriter methods which will skip applying quotes to all values.

Spring Security Remember Me Example

There are two methods in Spring Security for Remember Me service. One is using cookie in browser and the other one is using persistent. In this Spring Security Remember Me example, we will be using the persistent method which is more secured.

Spring Security Remember Me Example

These are the highlights of the example:
1. Create Persistence Table in database
2. Add Remember Me configuration in spring security context
3. Add Remember Me in your HTML

Create Persistence Table


Spring Security uses persistent_logins table use remember me. These table is constant so you don’t need to change the table names or the columns. Just add it to your database. Below is the definition of the persistent_logins table:

CREATE TABLE IF NOT EXISTS `db_name`.`persistent_logins` (
  `username` VARCHAR(100) NOT NULL,
  `series` VARCHAR(64) NOT NULL,
  `token` VARCHAR(64) NOT NULL,
  `last_used` TIMESTAMP NOT NULL,
  PRIMARY KEY (`series`));

where db_name is your database name. This will create the below ERD:

persistent_logins

persistent_logins

Configure Spring Security Context

After creating the database table, we now define the remember me service to our spring security context. Inside your spring security definition, add the remember me configs:


    <security:remember-me remember-me-parameter="remember-me"
                      remember-me-cookie="remember-me"
                      token-validity-seconds="604800"
                      data-source-ref="dataSource"/>

Here are the attribute definitions:

  • remember-me-parameter – this is the parameter name of your input tag in your html. Basically you will use an input type checkbox here.
  • remember-me-cookie – the name of the cookie that will be saved in browser
  • token-validity-seconds – determines the expiration time of the cookie in seconds
  • data-source-ref – this is the id of your bean definition of your datasource eg. your org.springframework.jdbc.datasource.DriverManagerDataSource

If you are also using a custom authentication success handler, you need to add the attribute authentication-success-handler-ref with its value as your bean definition of your custom authentication success handler. Read more about Spring Custom AuthenticationSuccessHandler Example

Add remember me in your HTML


Lastly, add the remember me input tag in your login html.
Inside your login form, add the input tag of your remember me, example:


Take note the attribute name is the one that we defined in our spring security context.
Then test it and if you have checked this input and logged in, it should add data to your persistent_table and save cookie to your browser.

Spring MVC Validation Order Example

In this spring mvc validation order, we will demonstrate how to use validation groups to set the order of validation. This is helpful when you want specific validation to be called first before other validators and since the default order of validators are not constant.

Spring MVC Validation Order Example

In order to create the validation order sequence, we must create an interface for the group, another interface for the sequence/order and in our controller we tell spring that it should use the sequence that we have defined.

Create Group Interface


For each group that you want to define, create an interface for that group.

public interface MatchGroup {
}

The interface is empty without any methods. Then we add that group interface to our validators that we want to be in that group. Example, we for this User Dto:

public class UserDto {

    @NotExistingLoginID
    private String loginID;

    @ShouldMatchField.ShouldMatch(groups = MatchGroup.class)
    private String password;

    @ShouldMatchField.ShouldMatch(groups = MatchGroup.class)
    private String confirmPassword;

    private int role;

...getters and setters
}

Here, the custom validator ShouldMatch was added in our created group interface MatchGroup. The validators such as NotExistingLoginID is not added in any group, thus, is in the Default group by default. Also read Custom Validator in Spring MVC

Create new interface for Sequence/Order

After defining the group interface, and setting it to our validators, now we create a new interface that will hold the validation sequence.

import javax.validation.GroupSequence;
import javax.validation.groups.Default;

@GroupSequence({Default.class, MatchGroup.class})
public interface ValidationSequence {
}


This is also an empty interface. Takenote of the @GroupSequence annotation. This is the annotation that holds the sequence. First it will run or call the validators that is in Default group. If the validators in the Default group succeeds without any validation errors, then it will call the next group MatchGroup. MatchGroup will not be called if the Default group has validation errors.

Configure Controller methods to use the Group Sequence

Now that the groups and sequence has been setup, lets now add it to our spring controller methods and tell them to use this group sequence.
To use this, in the parameter of your method, instead of using @Valid annotation, we will use @Validated annotation that will contain the ValidationSequence. For example:

@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
public String validateUser(@ModelAttribute("user_form") @Validated(ValidationSequence.class) UserDto userDto, BindingResult result) {
    if (result.hasErrors()) {
        return "user/error";
    }
    return "user/success";
}

And that’s it, you have already created your own validation sequence.

Spring MVC JSON Example

With Spring MVC Framework, its so much easy to map JSON String to Java Objects or convert Java Objects in to JSON string.

Spring MVC JSON Example

This will only take 3 steps to integrate JSON in your web project.

Configure Spring to Use Jackson

Spring 4 has already its own converter for JSON. You just need to add it to your message converters. To use it, go to your dispatcher-servlet.xml or your spring xml configuration and edit your mvc:annotation-driven:


    
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
    

Here, we used MappingJackson2HttpMessageConverter as its message converter.

Add Jackson Dependency in pom


Next, we add the jackson dependency in our pom.xml


    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    2.7.4


    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    2.7.4

Take note that we used version 2 of Jackson dependencies.

Configure your RequestMapping

Lastly, just add the produces attribute in your RequestMapping annotation. You can use MediaType.APPLICATION_JSON_VALUE or just the exact String “application/json”. Take a look at the below example:

@ResponseBody
@RequestMapping(value = "/search", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public List<Results> search(@ModelAttribute("search_form") SearchDto searchDto) {
    List<Results> results = results.getResults(searchDto);
    return results;
}

And Spring will automatically convert your java objects in to json format. Using Spring MVC Framework makes it easy to develop web applications.