如何将我的 json 文件格式化为多行

How to format my json-file to be multiple lines

我正在尝试使用 Jackson 写信给 json。它有效,据我所知它的格式正确。但是,它仍然只出现在 json 文件中的一行。它使阅读变得困难。有什么方法可以让它变成多行以便于阅读吗?

代码:

// "Tag" is the object.
String json = new Gson().toJson(tag);

// Writing the object to the json file
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("src/main/java/src/backend/json/toJson.json"), json);

toJson文件中的结果:

"{"name":"div","attributes":[{"type":"text","info":"Two"},{"type":"class","info":"test"},{"type":"id","info":"test2"}],"tagsContaining":[{"name":"divv ","attributes":[],"tagsContaining":[{"name":"a","attributes":[],"tagsContaining":[]}]},{"name":"div","attributes":[{"type":"text","info":"Two"}],"tagsContaining":[{"name":"a","attributes":[{"type" :"text","info":"Two"}],"tagsContaining":[]}]},{"name":"img","attributes":[],"tagsContaining":[]}]} “

如您所见,它被塞进了一行。 所以,我需要对其进行格式化,使其看起来像这样的 json 文件 :

{
  "name": "div",
  "attributes": [
    {
      "type": "text",
      "info": "Two"
    },
    {
      "type": "class",
      "info": "test"
    },
    {
      "type": "id",
      "info": "test2"
    } ...

我的标签class:

public class Tag {
    String name;
    ArrayList<Attribute> attributes;
    ArrayList<Tag> tagsContaining;

    public Tag() {
        this.attributes = new ArrayList<>();
        this.tagsContaining = new ArrayList<>();
    }

    public Tag(String name) {
        this.name = name;
        this.attributes = new ArrayList<>();
        this.tagsContaining = new ArrayList<>();
    }

    public void addAttribute(Attribute attribute) {
        attributes.add(attribute);
    }

    public void addTag(Tag tag) {
        tagsContaining.add(tag);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Tag{" +
                "name='" + name + '\'' +
                ", attributes=" + attributes +
                ", tagsContaining=" + tagsContaining +
                '}';
    }
}

要得到想要的结果,需要用到这个方法

ObjectMapper mapper = new ObjectMapper();
mapper.writerWithDefaultPrettyPrinter().writeValue(new FileWriter("src/main/java/src/backend/json/toJson.json"), tag);