Example usage for com.google.gson.stream JsonWriter setIndent

List of usage examples for com.google.gson.stream JsonWriter setIndent

Introduction

In this page you can find the example usage for com.google.gson.stream JsonWriter setIndent.

Prototype

public final void setIndent(String indent) 

Source Link

Document

Sets the indentation string to be repeated for each level of indentation in the encoded document.

Usage

From source file:Trainer.java

License:Apache License

private static void writeJsonArray(List list)
        throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, IOException {
    JsonWriter writer = new JsonWriter(new OutputStreamWriter(System.out));
    writer.setIndent("    ");
    JSONMarshaller.marshallArray(writer, list.toArray());
    writer.flush();//  w ww. j a va  2 s.c  om
}

From source file:at.yawk.votifier.VotifierKeyPair.java

License:Mozilla Public License

public void write(Writer writer, boolean pretty) throws IOException {
    JsonWriter w = new JsonWriter(writer);
    w.setIndent(pretty ? "    " : "");
    write(w);/*w  w  w  .  j  ava2  s .  c  om*/
}

From source file:classifiers.DummyClassifier.java

License:Apache License

public void parseStreamAndClassify(String jsonFile, String resultsFile) throws IOException {

    String journalName;//from   w  ww .  ja v a2s.  c o  m
    int count = 0;
    int abstract_count = 0;

    try {
        JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(jsonFile)));
        JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream(resultsFile), "UTF-8"));
        writer.setIndent("    ");

        //reader.setLenient(true);
        reader.beginArray();
        writer.beginArray();
        while (reader.hasNext()) {

            reader.beginObject();
            writer.beginObject();
            while (reader.hasNext()) {
                String name = reader.nextName();

                if (name.equals("abstract")) {
                    abstract_count++;
                    reader.skipValue();

                } else if (name.equals("pmid")) {
                    String pmid = reader.nextString();
                    writer.name("labels");
                    writeLabels(writer);
                    writer.name("pmid").value(pmid);
                } else if (name.equals("title")) {
                    reader.skipValue();
                } else {
                    System.out.println(name);
                    reader.skipValue();
                }
            }
            reader.endObject();
            writer.endObject();
        }
        reader.endArray();
        writer.endArray();

        System.out.println("Abstracts: " + abstract_count);

        writer.close();
    } catch (FileNotFoundException ex) {

    }
}

From source file:com.android.ide.common.blame.MergingLogPersistUtil.java

License:Apache License

/**
 * File format example for values files: (all paths are absolute)
 * <pre>[//from  w  w w . j a v  a 2  s.  c  o  m
 *     {
 *         "outputFile": "/path/build/intermediates/res/merged/f1/debug/values/values.xml",
 *         "map": [
 *             {
 *                 "to": {
 *                     "startLine": 2,
 *                     "startColumn": 4,
 *                     "startOffset": 55,
 *                     "endColumn": 54,
 *                     "endOffset": 105
 *                 },
 *                 "from": {
 *                     "file": "/path/src/f1/res/values/strings.xml",
 *                     "position": {
 *                         "startLine": 2,
 *                         "startColumn": 4,
 *                         "startOffset": 55,
 *                         "endColumn": 54,
 *                         "endOffset": 105
 *                     }
 *                 }
 *             },
 *             ...
 *         ]
 *     },
 *     ...
 * ]</pre>
 *
 * There should not be multiple object in the outer list for the same outputFile.
 */
static void saveToMultiFile(@NonNull File folder, @NonNull String shard,
        @NonNull Map<SourceFile, Map<SourcePosition, SourceFilePosition>> map) throws IOException {
    File file = getMultiFile(folder, shard);
    file.getParentFile().mkdir();
    JsonWriter out = new JsonWriter(Files.newWriter(file, Charsets.UTF_8));
    try {
        out.setIndent(INDENT_STRING);
        out.beginArray();
        for (Map.Entry<SourceFile, Map<SourcePosition, SourceFilePosition>> entry : map.entrySet()) {
            out.beginObject().name(KEY_OUTPUT_FILE);
            mSourceFileJsonTypeAdapter.write(out, entry.getKey());
            out.name(KEY_MAP);
            out.beginArray();
            for (Map.Entry<SourcePosition, SourceFilePosition> innerEntry : entry.getValue().entrySet()) {
                out.beginObject();
                out.name(KEY_TO);
                mSourcePositionJsonTypeAdapter.write(out, innerEntry.getKey());
                out.name(KEY_FROM);
                mSourceFilePositionJsonTypeAdapter.write(out, innerEntry.getValue());
                out.endObject();
            }
            out.endArray();
            out.endObject();
        }
        out.endArray();
    } finally {
        out.close();
    }
}

From source file:com.android.ide.common.blame.MergingLogPersistUtil.java

License:Apache License

/**
 * File format for single file blame./*from w  w w .ja  v a  2 s  . co  m*/
 * <pre>[
 *     {
 *         "merged": "/path/build/intermediates/res/merged/f1/debug/layout/main.xml",
 *         "source": "/path/src/main/res/layout/main.xml"
 *     },
 *     ...
 * ]</pre>
 * @param folder
 * @param shard
 * @param map
 * @throws IOException
 */
static void saveToSingleFile(@NonNull File folder, @NonNull String shard,
        @NonNull Map<SourceFile, SourceFile> map) throws IOException {
    File file = getSingleFile(folder, shard);
    file.getParentFile().mkdir();
    JsonWriter out = new JsonWriter(Files.newWriter(file, Charsets.UTF_8));
    try {
        out.setIndent(INDENT_STRING);
        out.beginArray();
        for (Map.Entry<SourceFile, SourceFile> entry : map.entrySet()) {
            out.beginObject();
            out.name(KEY_MERGED);
            mSourceFileJsonTypeAdapter.write(out, entry.getKey());
            out.name(KEY_SOURCE);
            mSourceFileJsonTypeAdapter.write(out, entry.getValue());
            out.endObject();
        }
        out.endArray();
    } finally {
        out.close();
    }
}

From source file:com.bazaarvoice.snitch.servlet.VariableServlet.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*  w  w w.j ava  2 s .com*/
protected void doGet(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {
    addClientNoCacheHeaders(response);
    response.setContentType("application/json");

    // Organize the variables into a multimap indexed by key
    Multimap<String, Variable> variables = HashMultimap.create();
    for (Variable variable : _snitch.getVariables()) {
        variables.put(variable.getName(), variable);
    }

    JsonWriter writer = new JsonWriter(new BufferedWriter(response.getWriter()));
    writer.setIndent("  "); // Pretty print by default

    try {
        writer.beginObject();
        for (String name : variables.keySet()) {
            Collection<Variable> vars = variables.get(name);

            writer.name(name);
            if (vars.size() > 1) {
                // Only render as an array if we have a name collision
                writer.beginArray();
            }
            for (Variable variable : vars) {
                Formatter formatter = _snitch.getFormatter(variable);
                formatter.format(variable.getValue(), writer);
            }
            if (vars.size() > 1) {
                writer.endArray();
            }
        }
        writer.endObject();
    } finally {
        Closeables.closeQuietly(writer);
    }
}

From source file:com.bedatadriven.rebar.appcache.linker.AppCacheIFrameLinker.java

License:Apache License

/**
 * The permutation map is used on the server side to serve the appropriate permutation
 *//*  w ww .j  a v a2  s .  c om*/
protected EmittedArtifact emitPermutationMap(TreeLogger logger, LinkerContext context, ArtifactSet artifacts)
        throws UnableToCompleteException {

    try {

        // Emit the selection script.
        StringWriter json = new StringWriter();
        JsonWriter writer = new JsonWriter(json);
        writer.setIndent("  ");

        SortedSet<CompilationResult> compilationResults = artifacts.find(CompilationResult.class);
        writer.beginArray();

        for (CompilationResult result : compilationResults) {
            for (SortedMap<SelectionProperty, String> map : result.getPropertyMap()) {
                writer.beginObject();
                writer.name("permutation").value(result.getStrongName());
                writer.name("properties");
                writer.beginObject();

                for (Map.Entry<SelectionProperty, String> property : map.entrySet()) {
                    writer.name(property.getKey().getName());
                    writer.value(property.getValue());
                }
                writer.endObject();
                writer.endObject();
            }
        }
        writer.endArray();
        return emitString(logger, json.toString(), "permutations");

    } catch (IOException e) {
        logger.log(TreeLogger.Type.ERROR, "Error writing permutation map", e);
        throw new UnableToCompleteException();
    }
}

From source file:com.commonslibrary.commons.utils.LogUtils.java

License:Open Source License

public static String prettyJson(String body) {
    if (TextUtils.isEmpty(body)) {
        return body;
    }/* www  .j  a  v  a 2  s  . c  om*/
    try {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        StringWriter stringWriter = new StringWriter();
        JsonWriter jsonWriter = new JsonWriter(stringWriter);
        jsonWriter.setIndent("\u00A0\u00A0");
        JsonElement jsonElement = new JsonParser().parse(body);
        gson.toJson(jsonElement, jsonWriter);
        return stringWriter.toString();
    } catch (JsonParseException e) {
        return body;
    }
}

From source file:com.esri.gpt.control.georss.Dcat11JsonFeedWriter.java

License:Apache License

@Override
public void write(IFeedRecords records) {
    Properties dcatProps = makeDefaultValues();
    DcatDefinition dcatDef = new DcatDefinition();

    JsonWriter jsonWriter = new JsonWriter(writer);
    jsonWriter.setIndent("  ");

    try {/*w ww.jav a2  s  .c  om*/
        dcatDef.print(jsonWriter, dcatProps, dcatSchemas, records);
    } catch (IOException ex) {
        Logger.getLogger(Dcat11JsonFeedWriter.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.example.feastbeast.ListViewRemovalAnimation.java

License:Apache License

public void writeJsonStream(OutputStream out, List<Recipe> messages) throws IOException {
    Gson gs = new Gson();
    JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));
    writer.setIndent("  ");
    writer.beginArray();//from  w w  w . j  a va  2s  .com
    for (Recipe message : messages) {
        gs.toJson(message, Recipe.class, writer);
    }
    writer.endArray();
    writer.close();
}