使用Java 6,Tomcat 7,Jersey 1.15,Jackson 1.9.9,创建了一个简单的Web服务,它具有以下架构:
我的POJO(模型类):
Family.java:
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Family {
private String father;
private String mother;
private List<Children> children;
// Getter & Setters
}
Children.java:
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Children {
private String name;
private String age;
private String gender;
// Getters & Setters
}
使用Utility Class,我决定按如下方式对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;
}
}
为MyWebService:
@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"
}
]
}
正在寻找一种实现的方法,因此它可以显示某种类型的带缩进/标签的格式。
如果有人可以帮助我,我将非常感激。
感谢您抽出宝贵时间阅读本文。
答案 0 :(得分:2)
您可以只返回一个字符串(Web服务调用者不会注意到差异),而不是返回一个Family。
@Path("")
public class MyWebService {
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getFamily {
// ObjectMapper instantiation and configuration could be static...
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
return mapper.writeValueAsString(FamilyUtil.getFamily());
}
}
虽然正如我在你对你的问题的评论中所说,你的服务真的不应该这样做。应该由Web服务调用者将响应格式化为他们需要的任何格式。
答案 1 :(得分:-1)
我能够通过使用以下代码来解决这个问题(不必要的引号和新行转义序列):
@GET
@Produces(MediaType.APPLICATION_JSON)
public Family getFamily() throws JsonGenerationException,
JsonMappingException,
IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
Family family = FamilyUtil.getFamily();
return mapper.readValue(mapper.writeValueAsString(family),
FamilyUtil.getFamily().getClass());
}
像这样使用curl:
curl -X GET http://localhost:8080/mywebservice
收率:
{"children":[{"age":"12","gender":"male","name":"Jimmy"}],"father":"Joe","mother":"Jennifer"}
似乎没有发生任何事......
以下是我的pom.xml文件中列出的依赖项:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.0.6</version>
</dependency>
有谁知道我可能做错了什么?
是否还有其他库让这一整体变得更容易?杰克逊似乎没有工作......