
net.anthavio.httl.util.JsonBuilder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hatatitla Show documentation
Show all versions of hatatitla Show documentation
Compact but tweakable REST client library you have been dreaming of
The newest version!
package net.anthavio.httl.util;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import javax.xml.bind.DatatypeConverter;
/**
* Jackson (JSON weapon of choice) is missing simple JSON strings builder.
* Other libraries are just too heavy for this quite simple job.
*
* By default, builder use ISO8601 date format and does NOT perform formatting and indentation
*
* Funny stuff with generics included!
*
* @author martin.vanek
*
*/
public class JsonBuilder {
private boolean indenting;
private int level = 0;
private StringBuilder sb = new StringBuilder();
private SimpleDateFormat dateFormat;
/**
* Start JSON object { ...
*
* Shorthand to new JsonBuilder().object()
*/
public static ObjectBuilder OBJECT() {
return new JsonBuilder().object();
}
/**
* Start JSON array { ...
*
* Shorthand to new JsonBuilder().array()
*/
public static ArrayBuilder ARRAY() {
return new JsonBuilder().array();
}
public JsonBuilder(boolean indenting, String dateFormat) {
this.indenting = indenting;
if (dateFormat != null) {
this.dateFormat = new SimpleDateFormat(dateFormat);
}
}
public JsonBuilder(boolean indenting) {
this(indenting, null);
}
public JsonBuilder(String dateFormat) {
this(false, dateFormat);
if (dateFormat == null) {
throw new IllegalArgumentException("DateFormat pattern is null");
}
}
public JsonBuilder() {
this(false, null);
}
public boolean isIndenting() {
return indenting;
}
public void setIndenting(boolean indenting) {
this.indenting = indenting;
}
public void setDateFormat(String pattern) {
this.dateFormat = new SimpleDateFormat(pattern);
}
/**
* Start Root JSON object
*/
public ObjectBuilder object() {
return new ObjectBuilder(this);
}
/**
* Shorthand to start JSON object with field as simple value
*/
public ObjectBuilder object(String fieldName, Object fieldValue) {
return new ObjectBuilder(this).field(fieldName, fieldValue);
}
/**
* Shorthand to start JSON object with field as nested object
*/
public ObjectBuilder> object(String fieldName) {
return new ObjectBuilder(this).object(fieldName);
}
/**
* Start Root JSON array
*/
public ArrayBuilder array() {
return new ArrayBuilder(this);
}
/**
* Shorthand to create simple JSON array out of collection
*/
public JsonBuilder array(Collection
© 2015 - 2025 Weber Informatics LLC | Privacy Policy