Ich benutze Moxy, um eine JSON-basierte API zu serialisieren. Funktioniert wie ein Charme, bis auf eine kleine Sache: Serialisierung eines Feldes mit einer URL als fieldName funktioniert nicht.MOXY unmarshal JSON mit URL in Feldname
Hier ist, was ich versuche zu erreichen:
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;
}
}
Prüfklasse:
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;
}
}
Jetzt ist die Ausgabe wie folgt aus:
{"http://www.foo.bar":"BAR","foo":"FOO","_foo_bar":"FOOBAR"}
null
FOO
FOOBAR
Also, die Frage ist: Wie behebe ich das Unmarshalling des ersten Attributs?
Um die moxy Bibliothek unmarshall json verwenden Sie benötigen [geben Sie die Eclipselaufzeit] (http://www.eclipse.org/eclipselink/documentation/2.4/moxy /runtime001.htm#CACFEGHC): '-Djavax.xml.bind.context.factory = org.eclipse.persistence.jaxb.JAXBContextFactory', Das ist keine Antwort, nur um zu untersuchen. – James
Danke James, ich habe vergessen, dies zu erwähnen, aber ich habe dies über eine Datei im Klassenpfad 'jaxb.properties' getan, die folgendes enthält: 'javax.xml.bind.context.factory = org.eclipse.persistence.jaxb.JAXBContextFactory' – user7595421