net.consensys.cava.toml.JsonSerializer Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of cava-toml Show documentation
Show all versions of cava-toml Show documentation
A parser for Tom's Obvious, Minimal Language (TOML).
The newest version!
/*
* Copyright 2018 ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package net.consensys.cava.toml;
import static java.util.Objects.requireNonNull;
import static net.consensys.cava.toml.TomlType.typeFor;
import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;
import java.util.Optional;
final class JsonSerializer {
private JsonSerializer() {}
static void toJson(TomlTable table, Appendable appendable) throws IOException {
requireNonNull(table);
requireNonNull(appendable);
toJson(table, appendable, 0);
appendable.append(System.lineSeparator());
}
private static void toJson(TomlTable table, Appendable appendable, int indent) throws IOException {
if (table.isEmpty()) {
appendable.append("{}");
return;
}
appendLine(appendable, "{");
for (Iterator iterator = table.keySet().stream().sorted().iterator(); iterator.hasNext();) {
String key = iterator.next();
append(appendable, indent + 2, "\"" + escape(key) + "\" : ");
Object value = table.get(Collections.singletonList(key));
assert value != null;
appendTomlValue(value, appendable, indent);
if (iterator.hasNext()) {
appendable.append(",");
appendable.append(System.lineSeparator());
}
}
appendable.append(System.lineSeparator());
append(appendable, indent, "}");
}
static void toJson(TomlArray array, Appendable appendable) throws IOException {
toJson(array, appendable, 0);
appendable.append(System.lineSeparator());
}
private static void toJson(TomlArray array, Appendable appendable, int indent) throws IOException {
if (array.isEmpty()) {
appendable.append("[]");
return;
}
if (array.containsTables()) {
append(appendable, 0, "[");
for (Iterator