我有一个 XML,我需要将其转换为 JSON,当在 XML 中我们有多个元素时,它会创建正确的 jsonArray,但是当单个元素未创建数组时,任何人都可以帮助我如何在单个元素的情况下获取数组
String TEST_XML_STRING = "<Items><Item><Name>Stack</Name><Name>OverFlow</Name></Item></Items>";
JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
// output - {"Items":{"Item":{"Name":["Stack","OverFlow"]}}}
when
String TEST_XML_STRING = "<Items><Item><Name>Stack</Name></Item></Items>";
JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
// output - {"Items":{"Item":{"Name":"Stack"}}}
但应该是{"Items":{"Item":[{"Name":"Stack"}]}}
我迟到了......但是,使用 org.json:
public static void forceToJSONArray(JSONObject xmlJSONObj, String obj) throws org.json.JSONException
{
// where "JSONObject xmlJSONObj" is my JSONObject obtained by passing the XML throug the method toJSONObject
// and where "String obj" is the name of the JSONObject I want to force to JSONArray
Object myObj = xmlJSONObj.opt(obj);
if (myObj == null)
{
// if my obj doesn't exist inside my xmlJSONObj i create it empty
JSONArray jsonArray = new JSONArray();
xmlJSONObj.put(obj, jsonArray);
}
else if ( myObj instanceof JSONObject )
{
// if exist but is a JSONObject, I force it to JSONArray
JSONObject myJSONObj = (JSONObject)myObj;
JSONArray jsonArray = new JSONArray();
jsonArray.put(myJSONObj);
xmlJSONObj.put(obj, jsonArray);
}
else if ( myObj instanceof String || myObj instanceof Integer )
{
// if exist but is a primitive entry (like in your case), I force it to a "primitive" JSONArray
JSONArray jsonArray = new JSONArray();
jsonArray.put(myObj);
xmlJSONObj.put(obj, jsonArray);
}
}
希望这能有所帮助;)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)