如何使用Jackson将对象的JSON文件读入Java列表中

时间:2017-05-19 03:40:40

标签: java json jackson

 public class Town {    

    private Person p;

    private String hello;
    private long number;
}

public class Person {

    private String firstName;
    private double legs;
    private String lastName;
}

我正在尝试使用以下代码将Town类编写为JSON

ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
 writer.writeValue(out, townobj);

这就产生了Json。

{
  "p" : {
    "firstName" : "John",
    "amount" : 6860.0,
    "lastName" : "Smith"
  },
  "hello" : "qwiejiowcqnio",
  "number" : 1380.0
}

{
  "p" : {
    "firstName" : "Sam",
    "amount" : 623460.0,
    "lastName" : "Smith"
  },
  "hello" : "qwiej2342io",
  "number" : 1330.0
}

如何使用jackson将嵌套对象产生的输出读入Java?

1 个答案:

答案 0 :(得分:2)

如果要将两个对象作为列表读入Java,则还需要将它们作为列表编写:

List<Town> towns = new ArrayList<>();
towns.add(townobj);
towns.add(anotherTownobj);

writer.writeValue(out, towns);

当你读回来时,它再次成为一个列表。

您在问题中显示的输出不是有效的单个json文件。但是使用上面的方法会得到一个有效的单个json文件,如下所示:

[
    {
      "p" : {
        "firstName" : "John",
        "amount" : 6860.0,
        "lastName" : "Smith"
      },
      "hello" : "qwiejiowcqnio",
      "number" : 1380.0
    },
    {
      "p" : {
        "firstName" : "Sam",
        "amount" : 623460.0,
        "lastName" : "Smith"
      },
      "hello" : "qwiej2342io",
      "number" : 1330.0
    }
]