XMLSerializer xmlSerializer = new XMLSerializer();
JSON json = xmlSerializer.read(xml);
return json.toString(3);
以上代码在xmll转成json字符串后,json字符串里会含有namespace属性,把下面的xml片断
<openremote xmlns="http://www.openremote.org" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:schemaLocation="http://www.openremote.org/panel.xsd">
转为
{ "@xmlns": "http://www.openremote.org", "@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance", "@xmlns:schemaLocation": "http://www.openremote.org/panel.xsd" }
但是这恰好是我不想要的属性。不用担心,只需给XMLSerializer加上设置属性skipNamespace为true即可,如下代码:
XMLSerializer xmlSerializer = new XMLSerializer();
xmlSerializer.setSkipNamespaces(true);
JSON json = xmlSerializer.read(xml);
return json.toString(3);
好,这一点就告一段落.
现在我又遇到了一个问题,那就是在xml里属性名为type的属性在转换后的json字符串中丢失了, 同样这一点也不用太担心,我看了一下XMLSerialzer的源码,发现XMLSerializer的构造器是这样写的:
public XMLSerializer() {
setObjectName( "o" );
setArrayName( "a" );
setElementName( "e" );
setTypeHintsEnabled( true );
setTypeHintsCompatibility( true );
setNamespaceLenient( false );
setSkipNamespaces( false );
setRemoveNamespacePrefixFromElements( false );
setTrimSpaces( false );
setExpandableProperties( EMPTY_ARRAY );
setSkipNamespaces( false );
}
其中
setTypeHintsEnabled( true );
setTypeHintsCompatibility( true );
就在搞鬼了, 因为在XMLSerialzer的
private JSON processObjectElement( Element element, String defaultType )
方法中还有这么一段把xml转为json的代码,如下:
// process attributes first
int attrCount = element.getAttributeCount();
for( int i = 0; i < attrCount; i++ ){
Attribute attr = element.getAttribute( i );
String attrname = attr.getQualifiedName();
if( isTypeHintsEnabled()
&& (addJsonPrefix( "class" ).compareToIgnoreCase( attrname ) == 0 || addJsonPrefix(
"type" ).compareToIgnoreCase( attrname ) == 0) ){
continue;
}
String attrvalue = attr.getValue();
setOrAccumulate( jsonObject, "@" + removeNamespacePrefix( attrname ),
trimSpaceFromValue( attrvalue ) );
}
addJsonPrefix的代码片断为
private String addJsonPrefix( String str ) {
if( !isTypeHintsCompatibility() ){
return JSON_PREFIX + str;
}
return str;
}
现在,你应该很清楚的可以看到当在构造器中
setTypeHintsEnabled(true);
setTypeHintsCompatibility(true);
的时候
if( isTypeHintsEnabled()
&& (addJsonPrefix( "class" ).compareToIgnoreCase( attrname ) == 0 || addJsonPrefix(
"type" ).compareToIgnoreCase( attrname ) == 0) )
也为true.
这样的话,type这个属性就被pass掉了。
所以,为了让type这个比较特殊的属性能在转换后的json字答串中出现,你只需对XMLSerialzer的实例这样做:
setTypeHintsEnabled(false);
或
setTypeHintsCompatibility(false);
或
setTypeHintsEnabled(false);
setTypeHintsCompatibility(false);
也就是说,反正让
if( isTypeHintsEnabled()
&& (addJsonPrefix( "class" ).compareToIgnoreCase( attrname ) == 0 || addJsonPrefix(
"type" ).compareToIgnoreCase( attrname ) == 0) )
为false就行,这样在xml中有type这个属性的时候就会转换为 "@type":"xxxx"
OK, 我的问题也解决。希望可以给你带来帮助。