All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ajjpj.abase.io.AJsonSerHelper Maven / Gradle / Ivy

Go to download

a-base is a library of basic (hence the name) classes, most notably immutable collection classes with copy-on-write operations

There is a newer version: 1.0-pre11
Show newest version
package com.ajjpj.abase.io;

import com.ajjpj.abase.collection.mutable.ArrayStack;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;


/**
 * This class is a collection of helper methods for manually writing JSON to an OutputStream. 

* * For details on the JSON spec, see http://json.org * * @author arno */ public class AJsonSerHelper { static final Charset UTF_8 = Charset.forName("UTF-8"); private static final int[] TEN_POW = new int[] {1, 10, 100, 1000, 10*1000, 100*1000, 1000*1000, 10*1000*1000, 100*1000*1000, 1000*1000*1000}; private static final String[] PATTERNS = new String[] {"0", "0.0", "0.00", "0.000", "0.0000", "0.00000", "0.000000", "0.0000000", "0.00000000", "0.000000000"}; private static final DecimalFormatSymbols DECIMAL_FORMAT_SYMBOLS = new DecimalFormatSymbols(Locale.US); private final Writer out; private final ArrayStack state = new ArrayStack< >(); public AJsonSerHelper(OutputStream out) { this.out = new OutputStreamWriter(out, UTF_8); state.push(JsonSerState.initial); } public void startObject() throws IOException { checkAcceptsValueAndPrefixComma(); state.push(JsonSerState.startOfObject); out.write("{"); } public void endObject() throws IOException { checkInObject(); state.pop(); out.write("}"); afterValueWritten(); } public void writeKey(String key) throws IOException { if(!state().acceptsKey) { throw new IllegalStateException("state " + state() + " does not accept a key"); } if(state() == JsonSerState.inObject) { out.write(","); } _writeStringLiteral(key); out.write(":"); state.push(JsonSerState.afterKey); } public void startArray() throws IOException { checkAcceptsValueAndPrefixComma(); state.push(JsonSerState.startOfArray); out.write("["); } public void endArray() throws IOException { checkInArray(); state.pop(); out.write("]"); afterValueWritten(); } public void writeStringLiteral(String s) throws IOException { checkAcceptsValueAndPrefixComma(); if(s == null) { writeNullLiteral(); } else { _writeStringLiteral(s); } afterValueWritten(); } private void _writeStringLiteral(String s) throws IOException { out.write('"'); for(int i=0; i





© 2015 - 2024 Weber Informatics LLC | Privacy Policy