我正在研究 maven SpringBoot 微服务应用程序,我希望 json 字符串带有我已经提到的根元素,但它给了我带有 ArrayList 作为根元素的 json 字符串。
报告了很多类似的问题,但没有一个解决方案对我有用。
预期是
{
"TestClass": [
{
"itemId": "000023",
"owner": "XYZ",
"name": "BMW"
},
{
"itemId": "000022",
"owner": "PQR",
"name": "GM"
},
{
"itemId": "000021",
"owner": "xyz",
"name": "Ford"
}
]
}
实际的 json 响应看起来像
{
"ArrayList": [
{
"itemId": "000023",
"owner": "XYZ",
"name": "BMW"
},
{
"itemId": "000022",
"owner": "PQR",
"name": "GM"
},
{
"itemId": "000021",
"owner": "xyz",
"name": "Ford"
}
]
}
POJO模型类
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("TestClass")
public class TestClass {
private String itemId;
private String owner;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
}
package com.apps.partnerecosystem.rest;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Named;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.teamcenter.hello.Hello;
@Named
@Path("/")
public class TestClassRest {
private static List<TestClass> clients = new ArrayList<TestClass>();
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<TestClass> getClientes() {
return clients;
}
@GET
@Path("list")
@Produces(MediaType.APPLICATION_JSON)
public List<TestClass> getList() {
List<TestClass> list = new ArrayList<TestClass>();
TestClassitem1 = new TestClass();
item1.setItemId("Test");
item1.setOwner("deshpapr");
item1.setName("Test");
list.add(item1);
list.add(item1);
return list;
}
}
应用程序配置文件
package com.apps.partnerecosystem.comappspartnerecosystem;
import javax.inject.Named;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
@Configuration
public class ApplicationConfig {
@Named
static class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
this.packages("com.apps.partnerecosystem.rest");
}
}
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.featuresToEnable(SerializationFeature.WRAP_ROOT_VALUE); // enables
// wrapping
// for
// root
// elements
builder.featuresToEnable(DeserializationFeature.UNWRAP_ROOT_VALUE);
return builder;
}
/*
* public RestTemplate restTemplate() { RestTemplate restTemplate = new
* RestTemplate(); restTemplate. return restTemplate; }
*/
}