gpt4 book ai didi

java - 当只有一个对象时将XML转换为Json数组Java

转载 作者:行者123 更新时间:2023-11-30 02:21:39 25 4
gpt4 key购买 nike

我有一个 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"]}}}

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);
}
}

希望这能有所帮助;)

关于java - 当只有一个对象时将XML转换为Json数组Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46666615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com