2

以下のコードを使用して、XML を Json に正常に変換しました。

この問題に遭遇しました。以下のプログラムに 2 つの異なる XML 文字列があります。

最初のものはユーザー名の単一の値を持ち、2 番目のものは 2 つの値を持ちます。

最初の xml は角括弧なしの json を生成し、2 番目の 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}}}}

上記のプログラムの 2 番目の XML は適切で、次のような出力が得られます。

{"Envelope":{"Header":{"authInfo":{"type":"soap:authentication","username":[null,null],"password":null}}}}

前もって感謝します。

4

1 に答える 1