简体   繁体   English

单项清单变成单项

[英]List of single item is turned into just a single item

I have a method which returns an object containing a list. 我有一个返回包含列表的对象的方法。 if the list is only one element long the JSON drops the '[' ']' which confuses our client software. 如果列表仅是一个元素长,那么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"}

]}}

I have used JAXB Based JSON support i used following call for change format of JSON response. 我使用了基于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;
     }

}

And configuration in Xml file for bean initialization. 并在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 
}

it will automatically change jersey producer result. 它将自动更改球衣生产者的结果。

you can read this https://jersey.java.net/documentation/1.18/json.html 您可以阅读此https://jersey.java.net/documentation/1.18/json.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM