我有一个返回包含列表的对象的方法。如果列表只有一个元素,则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"}
]}}
答案 0 :(得分:0)
我使用了基于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
}
它会自动改变球衣制作人的结果。