我使用JSON -simple,我需要漂亮地打印JSON数据(使其更易于阅读)。

我还没能在那个库中找到这个功能。 这通常是如何实现的?


当前回答

遵循JSON-P 1.0规范(JSR-353),对于给定的JsonStructure (JsonObject或JsonArray),一个更当前的解决方案可能是这样的:

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.json.Json;
import javax.json.JsonStructure;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;

public class PrettyJson {

    private static JsonWriterFactory FACTORY_INSTANCE;

    public static String toString(final JsonStructure status) {

        final StringWriter stringWriter = new StringWriter();

        final JsonWriter jsonWriter = getPrettyJsonWriterFactory()
                .createWriter(stringWriter);

        jsonWriter.write(status);
        jsonWriter.close();

        return stringWriter.toString();
    }

    private static JsonWriterFactory getPrettyJsonWriterFactory() {
        if (null == FACTORY_INSTANCE) {
            final Map<String, Object> properties = new HashMap<>(1);
            properties.put(JsonGenerator.PRETTY_PRINTING, true);
            FACTORY_INSTANCE = Json.createWriterFactory(properties);
        }
        return FACTORY_INSTANCE;
    }

}

其他回答

java有一个静态方法U.formatJson(json)。 支持5种格式类型:2,3,4,制表符和压缩。生活的例子

import com.github.underscore.U;

import static com.github.underscore.Json.JsonStringBuilder.Step.TABS;
import static com.github.underscore.Json.JsonStringBuilder.Step.TWO_SPACES;

public class MyClass {

    public static void main(String args[]) {
        String json = "{\"Price\": {"
        + "    \"LineItems\": {"
        + "        \"LineItem\": {"
        + "            \"UnitOfMeasure\": \"EACH\", \"Quantity\": 2, \"ItemID\": \"ItemID\""
        + "        }"
        + "    },"
        + "    \"Currency\": \"USD\","
        + "    \"EnterpriseCode\": \"EnterpriseCode\""
        + "}}";
        System.out.println(U.formatJson(json, TWO_SPACES)); 
        System.out.println(U.formatJson(json, TABS)); 
    }
}

输出:

{
  "Price": {
    "LineItems": {
      "LineItem": {
        "UnitOfMeasure": "EACH",
        "Quantity": 2,
        "ItemID": "ItemID"
      }
    },
    "Currency": "USD",
    "EnterpriseCode": "EnterpriseCode"
  }
}
{
    "Price": {
        "LineItems": {
            "LineItem": {
                "UnitOfMeasure": "EACH",
                "Quantity": 2,
                "ItemID": "ItemID"
            }
        },
        "Currency": "USD",
        "EnterpriseCode": "EnterpriseCode"
    }
}

GSON似乎支持这一点,尽管我不知道您是否想从正在使用的库切换。

来自用户指南:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);

遵循JSON-P 1.0规范(JSR-353),对于给定的JsonStructure (JsonObject或JsonArray),一个更当前的解决方案可能是这样的:

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.json.Json;
import javax.json.JsonStructure;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;

public class PrettyJson {

    private static JsonWriterFactory FACTORY_INSTANCE;

    public static String toString(final JsonStructure status) {

        final StringWriter stringWriter = new StringWriter();

        final JsonWriter jsonWriter = getPrettyJsonWriterFactory()
                .createWriter(stringWriter);

        jsonWriter.write(status);
        jsonWriter.close();

        return stringWriter.toString();
    }

    private static JsonWriterFactory getPrettyJsonWriterFactory() {
        if (null == FACTORY_INSTANCE) {
            final Map<String, Object> properties = new HashMap<>(1);
            properties.put(JsonGenerator.PRETTY_PRINTING, true);
            FACTORY_INSTANCE = Json.createWriterFactory(properties);
        }
        return FACTORY_INSTANCE;
    }

}

这将是一个公共方法,用于打印对象的漂亮版本(你需要安装Gson依赖项:

import com.google.gson.GsonBuilder;
...

public void printMe(){
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String prettyJSON = gson.toJson(this);
    System.out.println(printable);
}

使用org json。参考链接

JSONObject jsonObject = new JSONObject(obj);
String prettyJson = jsonObject.toString(4);

使用Gson。参考链接

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(obj);

使用杰克逊。参考链接

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(obj);

使用Genson的律师。参考链接。

Genson prettyGenson = new GensonBuilder().useIndentation(true).create();
String prettyJson = prettyGenson.serialize(obj);

使用javax.json。参考链接。

Map<String, Boolean> config = new HashMap<>();

config.put(JsonGenerator.PRETTY_PRINTING, true);

JsonWriterFactory writerFactory = Json.createWriterFactory(config);
Writer writer = new StringWriter();

writerFactory.createWriter(writer).write(jsonObject);

String json = writer.toString();

使用Moshi库。参考链接。

String json = jsonAdapter.indent("  ").toJson(emp1);

(OR)

Buffer buffer = new Buffer();
JsonWriter jsonWriter = JsonWriter.of(buffer);
jsonWriter.setIndent("   ");

jsonAdapter.toJson(jsonWriter, emp1);

json = buffer.readUtf8();