Sanitize JSON using Java

Introduction

Here I am going to tell you how to sanitize JSON (JavaScript Object Notation) string. Given JSON-like content, convert it to valid JSON. The OWASP JSON Sanitizer Project is a simple to use Java library that can be attached at either end of a data-pipeline to help satisfy Postel’s principle: be conservative in what you do, be liberal in what you accept from others.

When applied to JSON-like content from others, this project will produce well-formed JSON that should satisfy any parser you use. When applied to your output before you send, it will coerce minor mistakes in encoding and make it easier to embed your JSON in HTML and XML.

Prerequisites

Eclipse 2019-12, At least JDK 1.8, Maven or Gradle, JSON Sanitizer Library

Project Setup

You can create maven or gradle based project in Eclipse. The name of the project is java-sanitize-json.

If you are using maven as a build tool then you can use the below pom.xml file:

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.roytuts</groupId>
	<artifactId>java-sanitize-json</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<jdk.version>at least 1.8</jdk.version>
		<json-sanitizer.version>1.2.1</json-sanitizer.version>
	</properties>
	
	<dependencies>
		<!-- JSON sanitizer -->
		<dependency>
			<groupId>com.mikesamuel</groupId>
			<artifactId>json-sanitizer</artifactId>
			<version>${json-sanitizer.version}</version>
		</dependency>
	</dependencies>
	
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

If you are using gradle as a build tool then you can use below build.gradle script:

plugins {
    id 'java-library'
}

repositories {
    jcenter()
}

dependencies {
	implementation 'com.mikesamuel:json-sanitizer:1.2.1'
}

Sanitize JSON String

Create a JSON sanitizer class for sanitizing JSON string. You can pass invalid or valid JSON string as a parameter in the method jsonSanitize().

If you pass invalid JSON string then this library will make it valid JSON.

package com.roytuts.java.sanitize.json;

public class JsonSanitizer {

	public static String sanitizeJson(String jsonString) {
		String wellFormedJson = com.google.json.JsonSanitizer.sanitize(jsonString);
		return wellFormedJson;
	}

}

Test Class

Create a test class which will test whether it is sanitizing of the given JSON string or not. Here we will create a class with main method. You can also create Junit test class to test the above JSON sanitizer class.

In the below test class I am passing invalid JSON string for sanitization.

package com.roytuts.java.sanitize.json;

public class JsonSanitizerTest {

	public static void main(String[] args) {
		String jsonString = "{\"key1\":\"value1\",\"type\":\"Booking\",\"sid\":\"A43521\",\"region\":\"ASIA\","
				+ "\"fetchFromFile\":\"false\",\"service\":\"true\",\"isEom\":\"true\",*#@!}";

		String response = JsonSanitizer.sanitizeJson(jsonString);

		System.out.println(response);

		jsonString = "{\r\n" + 
				"    \"json_pino\" : {\r\n" + 
				"        \"title\" : \"JSON Pino log\",\r\n" + 
				"        \"description\" : \"JSON Pino log\",\r\n" + 
				"        \"hide-extra\": false,\r\n" + 
				"        \"multiline\": false,\r\n" + 
				"        \"json\" : true,\r\n" + 
				"        \"file-pattern\" : \"\\\\.json\",\r\n" + 
				"        \"level-field\" : \"level\",\r\n" + 
				"        \"level\": {\r\n" + 
				"            \"fatal\": 60,\r\n" + 
				"            \"error\": 50,\r\n" + 
				"            \"warning\": 40,\r\n" + 
				"            \"info\": 30,\r\n" + 
				"            \"debug\": 20,\r\n" + 
				"            \"trace\": 10\r\n" + 
				"        },\r\n" + 
				"        \"value\": {\r\n" + 
				"            \"pid\": { \"kind\": \"integer\", \"identifier\": true },\r\n" + 
				"            \"hostname\": { \"kind\": \"string\", \"identifier\": true },\r\n" + 
				"            \"level\": { \"kind\": \"integer\", \"identifier\": true },\r\n" + 
				"            \"time\": { \"kind\": \"integer\" },\r\n" + 
				"            \"msg\": { \"kind\": \"string\" },\r\n" + 
				"            \"v\": { \"kind\": \"integer\" },\r\n" + 
				"            \"responseTime\": { \"kind\": \"integer\" }\r\n" + 
				"        },\r\n" + 
				"        \"timestamp-field\": \"time\", hdjhdkjf\r\n" + 
				"        \"body-field\": \"msg\",\r\n" + 
				"        \"opid-field\": \"pid\",\r\n" + 
				"        \"line-format\" : [\r\n" + 
				"            { \"field\" : \"time\" , oiewui87325732},\r\n" + 
				"            \" \",\r\n" + 
				"            { \"field\" : \"msg\", \"default-value\": \"\" , jehjrgyutuew}\r\n" + 
				"        ],\r\n" + 
				"        \"sample\": [\r\n" + 
				"            {\r\n" + 
				"                \"line\": \"{\\\"pid\\\":31839,\\\"hostname\\\":\\\"ip-172-31-11-174\\\",\\\"level\\\":30,\\\"time\\\":1494255536591,\\\"msg\\\":\\\"request completed\\\",\\\"responseTime\\\":1,\\\"v\\\":1, hgdsfd7635732}\"\r\n" + 
				"            }\r\n" + 
				"        ]\r\n" + 
				"    }\r\n" + 
				"}";

		response = JsonSanitizer.sanitizeJson(jsonString);

		System.out.println(response);
	}

}

Testing the JSON sanitizer

Once you run the test class, you will see the output in the console.

{"key1":"value1","type":"Booking","sid":"A43521","region":"ASIA","fetchFromFile":"false","service":"true","isEom":"true"}
{
    "json_pino" : {
        "title" : "JSON Pino log",
        "description" : "JSON Pino log",
        "hide-extra": false,
        "multiline": false,
        "json" : true,
        "file-pattern" : "\\.json",
        "level-field" : "level",
        "level": {
            "fatal": 60,
            "error": 50,
            "warning": 40,
            "info": 30,
            "debug": 20,
            "trace": 10
        },
        "value": {
            "pid": { "kind": "integer", "identifier": true },
            "hostname": { "kind": "string", "identifier": true },
            "level": { "kind": "integer", "identifier": true },
            "time": { "kind": "integer" },
            "msg": { "kind": "string" },
            "v": { "kind": "integer" },
            "responseTime": { "kind": "integer" }
        },
        "timestamp-field": "time", "hdjhdkjf"
        :"body-field" ,"msg"
        :"opid-field" ,"pid"
        :"line-format"  ,"":[
            { "field" : "time" , "oiewui87325732":null},
            " ",
            { "field" : "msg", "default-value": "" , "jehjrgyutuew":null}
        ],
        "sample": [
            {
                "line": "{\"pid\":31839,\"hostname\":\"ip-172-31-11-174\",\"level\":30,\"time\":1494255536591,\"msg\":\"request completed\",\"responseTime\":1,\"v\":1, hgdsfd7635732}"
            }
        ]
    }
}

Source Code

Download

Thanks for reading.

Related posts

2 Thoughts to “Sanitize JSON using Java”

  1. Samir

    Hi,
    How to sanitize an object .
    Suppose that i have a class Person class to be sent as a json response from my REST call then how can i sanitize this Java class.

    1. I don’t think you need to sanitize Java class but if you still need then you can convert class to json and sanitize the output json.

Leave a Comment