Java JSON Object Jackson

Java JSON Jackson

To convert Java object to JSON and JSON to Java many API are available and if you are looking for extensive one which could be use in any Java project then Jackson API is very suitable. Here I will show you how to achieve Java JSON conversion using Jackson API:

  • JsonConversionUsingJackson.java:
package com.javahonk;

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

import org.json.simple.parser.ParseException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonConversionUsingJackson {
	
	public static void main(String[] args) throws ParseException, IOException {
		
		//Convert single java object to JSON Java vice versa
		Peoples peoples = new Peoples("tset", "lastName", 15);
		ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(peoples);
        
        //Converted to JSON string
        System.out.println(json);
        
        //Convert from JSON string to Java again
        Peoples peoples2 = (Peoples)mapper.readValue(json, Peoples.class);
        System.out.println(peoples2);
        
        //Convert list of java object to JSON Java vice versa
        List<Peoples> list = new ArrayList<Peoples>();
        list.add(new Peoples("tset", "lastName", 15));
        list.add(new Peoples("tset1", "lastName1", 25));
        list.add(new Peoples("tset2", "lastName2", 35));
        
        json = mapper.writeValueAsString(list);
        
        //Converted to JSON string
        System.out.println(json);
        
        //Convert from JSON string to Java again
        Peoples peoples3[] = mapper.readValue(json, Peoples[].class);
        for (int i = 0; i < peoples3.length; i++) {
			Peoples peoples4 = peoples3[i];
			System.out.println(peoples4);			
		}
		
	}

}

class Peoples {
	
	private String firstName;
	private String lastName;
	private int age;
	
	public Peoples(){}
	
	public Peoples(String firstName, String lastName, int age) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}
	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 int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Peoples [firstName=" + firstName + ", lastName=" + lastName
				+ ", age=" + age + "]";
	}
	
}
  • Output:

Java JSON Jackson

Leave a Reply

Your email address will not be published. Required fields are marked *