【问题标题】:How to format my json-file to be multiple lines [duplicate]如何将我的json文件格式化为多行[重复]
【发布时间】:2021-07-06 01:54:47
【问题描述】:

我正在尝试使用 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"
    } ...

我的标签类:

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 +
                '}';
    }
}

【问题讨论】:

  • 你为什么同时使用 2 个不同的 JSON 库?

标签: java json intellij-idea jackson


【解决方案1】:

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

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

【讨论】:

  • 很难使用这个迷你评论框...使用@ArmDuke 方法我得到了正确的格式。但它只做{“name”:“div”}。 tag-object 包含String name,和两个arraylist:attributes 和tagscontaining。好像没有写数组列表
  • 更新/编辑了问题,使其包含 Tag 类
  • 确保您的 Tag 类对这些字段有适当的 getter 和 setter 方法
猜你喜欢
  • 1970-01-01
  • 2019-08-06
  • 2020-09-15
  • 2013-11-27
  • 1970-01-01
  • 1970-01-01
  • 2014-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多