Using Jackson to parse JSON

package com.adx.web.member.service;
import static org.junit.Assert.*;
import org.apache.commons.lang3.StringEscapeUtils;
import org.junit.Before;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JacksonTest {
	private Singleton singleton;
	@Before
	public void setUp(){
		singleton = Singleton.getInstance();
		singleton.setName("John");
	}	
	@Test
	/**
	 * We use JACKSON to process JSON data
	 *  Example - an be used to convert a JSON object as a  String  (com.fasterxml.jackson.databind writeValueAsString )
	 *   
	*/
	public void  jackSonTest () throws Exception{
		assertNotNull(singleton.getName());
		assertNotNull( Util.serializeJSONWithNonNull(singleton)); //{\"name\":\"John\"}
	}
	/** In Javascript, we can use JQUERY to parse JSON
		var obj = $.parseJSON('{ "name": "John" }' );
		alert( obj.name === "John" );
	*/
	}

final class Singleton {
    private static final Singleton INSTANCE = new Singleton();
    private String name;
    private Singleton() {
        if (Singleton.INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");
        }
    }
    public static Singleton getInstance() {
        return Singleton.INSTANCE;
    }
    public void setName(String name) {
    	this.name = name;
	}
	public String getName() {
		return name;
	}
}


class  Util {
	// We use JACKSON  com.fasterxml.jackson.databind to convert a JSON object as a  String
	public static String serializeJSONWithNonNull(Object object) throws Exception{
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
		mapper.setSerializationInclusion(Include.NON_NULL);
		return  EscapedJSON( mapper.writeValueAsString(object));
	}
	private static  String EscapedJSON(String jsonStr){
		  return  StringEscapeUtils.escapeEcmaScript(jsonStr);
	}
}

Published by anthonykuong

Anthony is a versatile Software professional with around 10 years of experience. He is a Full Stack developer experienced with clients in the Financial, Health and Supply Chain industries. He is experienced with MVC frameworks ( Spring Boot) , SPA frameworks ( Angular , VueJS), and also supports automated build deployments and packaging for development, qa, and production servers.. He has delivered rich user experience using Modern web technologies and techniques such are HTML5, CSS3, ECMAScript 6 (ES6)/ ECMAScript 2015, CSS pre-processors (SASS, Less), JavaScript build tools (Grunt, Gulp) , various UI Frameworks including AngularJS , Knockout JS , and CSS Frameworks including Bootstrap, and Foundation. He is adaptable to new technologies and frameworks. He is a rigorous, quality-conscious contributor with solid analytical skills. I can also be found on youtube - Youtube Channel: https://www.youtube.com/user/akuong/

Leave a comment