我使用下面的代码成功地将我的 XML 转换为 Json。
我遇到了这个问题,我在下面的程序中有两个不同的 XML 字符串。
第一个具有单个用户名值,第二个具有两个值。
第一个 xml 生成没有方括号的 json。第二个 xml 生成方括号。
我希望他们两个都有方括号。有没有办法将用户名强制转换为输出字符串中的数组?
首先,我希望它们看起来像输出 json 中的数组。
package com.java.json;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.xml.XMLSerializer;
public class XmlSerializer {
public static void main(String[] args) throws Exception {
String xmlstring = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://services.web.post.list.com\"><soapenv:Header><authInfo xsi:type=\"soap:authentication\" xmlns:soap=\"http://list.com/services/SoapRequestProcessor\"><!--You may enter the following 2 items in any order--><username xsi:type=\"xsd:string\">user@email.com</username><password xsi:type=\"xsd:string\">password</password></authInfo></soapenv:Header></soapenv:Envelope>";
//String xmlstring = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://services.web.post.list.com\"><soapenv:Header><authInfo xsi:type=\"soap:authentication\" xmlns:soap=\"http://list.com/services/SoapRequestProcessor\"><!--You may enter the following 2 items in any order--><username xsi:type=\"xsd:string\">user@email.com</username><username xsi:type=\"xsd:string\">user@email.com</username><password xsi:type=\"xsd:string\">password</password></authInfo></soapenv:Header></soapenv:Envelope>";
JsonConfig conf = new JsonConfig();
XMLSerializer xs = new XMLSerializer();
xs.setForceTopLevelObject(true);
xs.setSkipWhitespace(true);
xs.setTrimSpaces(true);
xs.setSkipNamespaces(true);
xs.setRemoveNamespacePrefixFromElements(true);
JSONObject jsonobj = (JSONObject) xs.read(xmlstring);
String jsonstring = jsonobj.toString().replace("\"@", "\"");
System.out.println(jsonstring);
}
}
第一个 XML 应该给出这样的输出。
{"Envelope":{"Header":{"authInfo":{"type":"soap:authentication","username":[null],"password":null}}}}
目前它是这样给予的。
{"Envelope":{"Header":{"authInfo":{"type":"soap:authentication","username":null,"password":null}}}}
上面程序中的第二个 XML 很好,它给出了这样的输出。
{"Envelope":{"Header":{"authInfo":{"type":"soap:authentication","username":[null,null],"password":null}}}}
提前致谢。