Thursday, 22 June 2017

How to Convert JSON data from file to ArrayList?

In below example file student_data.txt having collections of students data in JSON form and through these Jacson API’s will convert JSON data to ArrayList java object.

Pre-Requisite 


Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

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

Sample Data


 Add below content in  student_data.txt

[
{
  "rollNumber" : 11,
  "firstName" : "Saurabh",
  "lastName" : "Gupta",
  "permanent" : false,
  "address" : {
    "addressLine" : "Lake Union Hill Way",
    "city" : "Atlanta",
    "zipCode" : 50005
  },
  "phoneNumbers" : [ 2233445566, 3344556677 ],
  "cities" : [ "Dallas", "San Antonio", "Irving" ],
  "properties" : {
    "play" : "Badminton",
    "interst" : "Math",
    "age" : "34 years"
  }
},
{
  "rollNumber" : 11,
  "firstName" : "Gaurav",
  "lastName" : "Khaira",
  "permanent" : true,
  "address" : {
    "addressLine" : " 5770 Shiloh woods dr",
    "city" : "Cumming",
    "zipCode" : 50007
  },
  "phoneNumbers" : [ 2233445567, 3344556678 ],
  "cities" : [ "New York", "Austin", "Plano" ],
  "properties" : {
    "play" : "Baseball",
    "interst" : "Science",
    "age" : "36 years"
  }
}
]

Example 


package test.facingissesonit.json.jacson;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ConvertJsonToArrayList {

    public static void main(String[] args) {
        try
        {
        byte[] mapData = Files.readAllBytes(Paths.get("student_data.txt"));
        Student[] studentArr = null;

        ObjectMapper objectMapper = new ObjectMapper();
        studentArr = objectMapper.readValue(mapData, Student[].class);
        List<Student> studentList=Arrays.asList(studentArr);
        System.out.println("Student 1 \n"+studentList.get(0));
        System.out.println("Student 2 \n"+studentList.get(1));

        }
        catch(JsonMappingException ex)
        {
            ex.printStackTrace();
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }
    }
}

Model Classes


Below Student and Address are required classes for execute this code.

package test.facingissesonit.json.jacson;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Student {
    private int rollNumber;
    private String firstName;
    private String lastName;
    private boolean permanent;
    private Address address;
    private long[] phoneNumbers;
    private List<String> cities;
    private Map<String, String> properties;
    @Override
    public String toString()
    {
        StringBuffer sb=new StringBuffer();
        sb.append("==============Student Information================\n");
        sb.append("rollNumber=").append(rollNumber).append("\n");
        sb.append("firstName=").append(firstName).append("\n");
        sb.append("lastName=").append(lastName).append("\n");
        sb.append("permanent=").append(permanent).append("\n");
        sb.append("adress=").append(address).append("\n");
        sb.append("phoneNumbers=").append(Arrays.toString(phoneNumbers)).append("\n");
        sb.append("cities=").append(Arrays.toString(cities.toArray(new String[cities.size()]))).append("\n");
        sb.append("properties=").append(properties).append("\n");
        return sb.toString();
    }
    public int getRollNumber() {
        return rollNumber;
    }
    public void setRollNumber(int rollNumber) {
        this.rollNumber = rollNumber;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public boolean isPermanent() {
        return permanent;
    }
    public void setPermanent(boolean permanent) {
        this.permanent = permanent;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public long[] getPhoneNumbers() {
        return phoneNumbers;
    }
    public void setPhoneNumbers(long[] phoneNumbers) {
        this.phoneNumbers = phoneNumbers;
    }
    public List<String> getCities() {
        return cities;
    }
    public void setCities(List<String> cities) {
        this.cities = cities;
    }
    public Map<String, String> getProperties() {
        return properties;
    }
    public void setProperties(Map<String, String> properties) {
        this.properties = properties;
    }

}

package test.facingissesonit.json.jacson;

public class Address {
private String addressLine;
private String city;
private String state;
private int zipCode;
@Override
public String toString()
{
    StringBuffer sb=new StringBuffer();
    sb.append("AddressLine=").append(addressLine).append("\n");
    sb.append("city=").append(city).append("\n");
    sb.append("state=").append(state).append("\n");
    sb.append("zipCode=").append(zipCode).append("\n");
    return sb.toString();
}
public String getAddressLine() {
    return addressLine;
}
public void setAddressLine(String addressLine) {
    this.addressLine = addressLine;
}
public String getCity() {
    return city;
}
public void setCity(String city) {
    this.city = city;
}
public String getState() {
    return state;
}
public void setState(String state) {
    this.state = state;
}
public int getZipCode() {
    return zipCode;
}
public void setZipCode(int zipCode) {
    this.zipCode = zipCode;
}
}

Output


Below is console output generated by program which is from Java Object.

Student 1
==============Student Information================
rollNumber=11
firstName=Saurabh
lastName=Gupta
permanent=false
adress=AddressLine=Lake Union Hill Way
city=Atlanta
state=null
zipCode=50005

phoneNumbers=[2233445566, 3344556677]
cities=[Dallas, San Antonio, Irving]
properties={play=Badminton, interst=Math, age=34 years}

Student 2
==============Student Information================
rollNumber=11
firstName=Gaurav
lastName=Khaira
permanent=true
adress=AddressLine= 5770 Shiloh woods dr
city=Cumming
state=null
zipCode=50007

phoneNumbers=[2233445567, 3344556678]
cities=[New York, Austin, Plano]
properties={play=Baseball, interst=Science, age=36 years}