0
我正在使用Moxy序列化基於JSON的API。 除了一件小事情之外,它像一個魅力一樣工作: 使用URL作爲fieldName序列化字段不起作用。MOXY解組JSON與字段名稱中的URL
這裏就是我想要實現:
讓Foo.class:
package test;
import javax.xml.bind.annotation.XmlElement;
public class Foo {
@XmlElement(name = "http://www.foo.bar")
private String bar;
private String foo;
@XmlElement(name = "_foo_bar")
private String fooBar;
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
public String getFooBar() {
return fooBar;
}
public void setFooBar(String fooBar) {
this.fooBar = fooBar;
}
}
測試類:
package test;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class TestMoxy {
public static void main(String[] args) {
String json = "{\"http://www.foo.bar\":\"BAR\",\"foo\":\"FOO\",\"_foo_bar\":\"FOOBAR\"}";
System.out.println(json);
Foo f = unMarshal(json);
System.out.println(f.getBar());
System.out.println(f.getFoo());
System.out.println(f.getFooBar());
}
public static Foo unMarshal(final String jsonString) {
try {
Map<String, Object> properties = new HashMap<String, Object>(2);
properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
JAXBContext jc = JAXBContext.newInstance(new Class[] {Foo.class}, properties);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StringReader reader = new StringReader(jsonString);
Foo f = unmarshaller.unmarshal(new StreamSource(reader),Foo.class).getValue();
return f;
} catch (final JAXBException e) {
e.printStackTrace();
}
return null;
}
}
現在的輸出是這樣的:
{"http://www.foo.bar":"BAR","foo":"FOO","_foo_bar":"FOOBAR"}
null
FOO
FOOBAR
所以,問題是:如何解決第一個屬性的解組?
要使用莫西庫來解讀JSON,你需要[指定的EclipseLink運行時(http://www.eclipse.org/eclipselink/documentation/2.4/moxy /runtime001.htm#CACFEGHC):'-Djavax.xml.bind.context.factory = org.eclipse.persistence.jaxb.JAXBContextFactory',這不是一個答案,只是爲了幫助調查。 – James
謝謝詹姆斯,我忘了提到這一點,但我通過類路徑'jaxb.properties'中包含以下內容的文件完成:'javax.xml.bind.context.factory = org.eclipse.persistence.jaxb.JAXBContextFactory' – user7595421