使用 Java 6、Tomcat 7、Jersey 1.15、Jackson 1.9.9,创建了一个具有以下架构的简单 Web 服务:
我的 POJO(模型类):
家庭.java:
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Family {
private String father;
private String mother;
private List<Children> children;
// Getter & Setters
}
儿童.java:
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Children {
private String name;
private String age;
private String gender;
// Getters & Setters
}
使用实用程序类,我决定对 POJO 进行硬编码,如下所示:
public class FamilyUtil {
public static Family getFamily() {
Family family = new Family();
family.setFather("Joe");
family.setMother("Jennifer");
Children child = new Children();
child.setName("Jimmy");
child.setAge("12");
child.setGender("male");
List<Children> children = new ArrayList<Children>();
children.add(child);
family.setChildren(children);
return family;
}
}
我的网络服务:
@Path("")
public class MyWebService {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Family getFamily {
return FamilyUtil.getFamily();
}
}
产生:
{"children": [{"age":"12","gender":"male","name":"Jimmy"}],"father":"Joe", "mother":"Jennifer"}
我需要做的是让它以更清晰的方式生成它:
{
"father":"Joe",
"mother":"Jennifer",
"children":
[
{
"name":"Jimmy",
"age":"12","
"gender":"male"
}
]
}
只是在寻找一种实现方式,以便它可以显示某种带有缩进/制表符的格式。
如果有人可以帮助我,将不胜感激。
感谢您抽出时间来阅读。