# Class JsonWriter

java.lang.Object
uk.ac.starlink.ttools.taplint.JsonWriter

public class JsonWriter extends Object
Outputs an object as JSON. Classes List, Map, Number and Boolean are recognised. Arrays are not. If there is a non-string where a string is required, it's just forced to a string by calling its toString method.

Since:
  23 Oct 2016
Author:
  Mark Taylor

## Constructor Summary

Constructors
Constructor
Description
`JsonWriter()`
Constructor with default properties.
`JsonWriter(int indent, boolean spacer)`
Custom constructor.

## Method Summary

Modifier and Type
Method
Description
`String`
`getIndent(int level)`
Returns prepended whitespace.
`String`
`jsonPair(String key, Object value, int level, boolean isPositioned)`
Serialises a key-value pair to JSON.
`String`
`toJson(Object item)`
Converts an item to JSON.
`void`
`toJson(StringBuffer sbuf, Object item, int level, boolean isPositioned)`
Recursive method which does the work for conversion.

### Methods inherited from class Object

`clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

## Constructor Details

### JsonWriter

public JsonWriter()
Constructor with default properties.

### JsonWriter

public JsonWriter(int indent, boolean spacer)
Custom constructor.

Parameters:
  `indent` - number of characters indent per level
  `spacer` - whether to put spaces inside brackets

## Method Details

### toJson

public String toJson(Object item)
Converts an item to JSON.

Parameters:
  `item` - suitable object
Returns:
  JSON representation

### toJson

public void toJson(StringBuffer sbuf, Object item, int level, boolean isPositioned)
Recursive method which does the work for conversion. If possible, call this method with `isPositioned=false`.

Parameters:
  `sbuf` - string buffer to append result to
  `item` - object to convert
  `level` - current indentation level
  `isPositioned` - true if output should be direct to sbuf, false if it needs a newline plus indentation first

### getIndent

public String getIndent(int level)
Returns prepended whitespace.

Parameters:
  `level` - indentation level
Returns:
  string to prepend

### jsonPair

public String jsonPair(String key, Object value, int level, boolean isPositioned)
Serialises a key-value pair to JSON.

Parameters:
  `key` - key string
  `value` - value object
  `level` - indentation level
  `isPositioned` - true if output should be direct to sbuf, false if it needs a newline plus indentation first
Returns:
  pair representation