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

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

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

import com.ajjpj.afoundation.collection.mutable.AStack;

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 AStack state = new AStack<>(); 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 { if (s == null) { writeNullLiteral (); return; } checkAcceptsValueAndPrefixComma(); _writeStringLiteral(s); afterValueWritten(); } private void _writeStringLiteral(String s) throws IOException { out.write('"'); for(int i=0; i





© 2015 - 2024 Weber Informatics LLC | Privacy Policy