Java 在jersey中使用JAXB将JSON字符串呈现为JSON
对于这样一个类:Java 在jersey中使用JAXB将JSON字符串呈现为JSON,java,json,jaxb,jersey,Java,Json,Jaxb,Jersey,对于这样一个类: @XmlRootElement public class MyClass { private Boolean flag1; private String json; ... } 我是否可以添加一个注释,使JSON成为呈现JSON的一部分,而不作为字符串转义 例如,如果对象具有flag1=true和json=“{a:5}”我想要得到: {"flag":true,"json":{"a":5}} 而不是: {"flag":true,"json":"{\"a
@XmlRootElement
public class MyClass {
private Boolean flag1;
private String json;
...
}
我是否可以添加一个注释,使JSON成为呈现JSON的一部分,而不作为字符串转义
例如,如果对象具有flag1=true
和json=“{a:5}”
我想要得到:
{"flag":true,"json":{"a":5}}
而不是:
{"flag":true,"json":"{\"a\":5}"}
您可以编写自己的封送拆收器来执行此操作。您可以使用提供程序更改JSONJAXBContext的默认行为。看
导入javax.ws.rs.ext.ContextResolver;
导入javax.ws.rs.ext.Provider;
导入javax.xml.bind.JAXBContext;
导入javax.xml.bind.JAXBException;
导入com.sun.jersey.api.json.json配置;
导入com.sun.jersey.api.json.JSONJAXBContext;
@提供者
公共类CustomWoodingOutputJSOnContextProvider实现ContextResolver{
私有JAXBContext上下文;
私有类[]类型={MyClass.Class};
public customWoodingOutputJSOnContextProvider()抛出JAXBEException{
this.context=newJSONJAXBContext(JSONConfiguration.natural().build(),类型);
}
公共JAXBContext getContext(类objectType){
for(int i=0;i
}目前这对我来说有点太多了。我希望有更简单的东西。但也许它会帮助其他人。出于我自己的需要,我将其作为字符串保留,并在客户端进行json解析。
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.api.json.JSONJAXBContext;
@Provider
public class CustomWoodwingOutputJSONContextProvider implements ContextResolver<JAXBContext> {
private JAXBContext context;
private Class<?>[] types = { MyClass.class };
public CustomWoodwingOutputJSONContextProvider() throws JAXBException {
this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), types);
}
public JAXBContext getContext(Class<?> objectType) {
for (int i = 0; i < this.types.length; i++)
if (this.types[i].equals(objectType))
return context;
return null;
}