[英]List of single item is turned into just a single item
我有一个返回包含列表的对象的方法。 如果列表仅是一个元素长,那么JSON会删除“ [“']”,这会使我们的客户端软件感到困惑。
@GET
@Path("list")
@Produces("application/json")
public Three findThreeList()
{ One one = new One(); one.setFirst("previous"); List<One> ones = new ArrayList<One>(1); ones.add(one); Three three = new Three(); three.setOnes(ones); log.info(three); return three; }
generated output without brackets:
{"three":{"ones":
{"first":"previous"}
}}
if multi items in list it's correct:
{"three":{"ones":[
{"first":"previous"}
,
{"first":"next"}
]}}
我使用了基于JAXB的JSON支持,以下调用了JSON响应的更改格式。
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.Produces;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import org.springframework.stereotype.Component;
import com.ws.convertors.EmployeeTimeTrackingConvertor;
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.api.json.JSONJAXBContext;
@Provider
@Component
@SuppressWarnings("unchecked")
@Produces("application/json")
public class JAXBContextResolver implements ContextResolver<JAXBContext>{
private Class[] types = { EmployeeTimeTrackingConvertor.class};
private JAXBContext context;
private final Set<Class> typeSet;
public JAXBContextResolver() throws Exception {
this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), types);
this.typeSet = new HashSet(Arrays.asList(types));
}
public JAXBContext getContext(Class<?> objectType) {
return (typeSet.contains(objectType)) ? context : null;
}
}
并在Xml文件中配置以进行bean初始化。
@XmlRootElement(name = "employeeTimeTracking")
public class EmployeeTimeTrackingConvertor {
private EmployeeTimeTrackingWrapper employeeTimeTrackingWrapper;
private Integer returnCode=null;
private List<EmployeeTimeTrackingWrapper> employeeTimeTrackingWrapperList;
private List<EmployeeLeaveStatusHistoryNewWrapper> timeOffHistoryList;
-----setter and getter methods
}
它将自动更改球衣生产者的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.