如何在Java中将XML转换为JSON数组?

PHPz
PHPz 转载
2023-09-14 23:01:02 843浏览

如何在Java中将XML转换为JSON数组?

JSON 是一种轻量级的数据交换格式,JSON 的格式类似于键值对。我们可以使用org.json.XML类XML转换为JSON数组,这提供了一个静态方法,XML.toJSONObject() 将 XML 转换为 JSON 数组。

public static JSONObject toJSONObject(java.lang.String string) throws JSONException

在下面的示例中,将 XML 转换为 JSON 数组

示例

import org.json.*;
public class ConvertXMLToJSONArrayTest {
   public static String xmlString= "<?xml version=\"1.0\" ?><root><test       attrib=\"jsontext1\">tutorialspoint</test><test attrib=\"jsontext2\">tutorix</test></root>";
   public static void main(String[] args) {
      try {
         JSONObject json = XML.toJSONObject(xmlString); // converts xml to json
         String jsonPrettyPrintString = json.toString(4); // json pretty print
         System.out.println(jsonPrettyPrintString);
      } catch(JSONException je) {
         System.out.println(je.toString());
      }
   }
}

输出

{"root": {"test": [
    {
    "attrib": "jsontext1",
    "content": "tutorialspoint"
    },
    {
    "attrib": "jsontext2",
    "content": "tutorix"
    }
]}}

以上就是如何在Java中将XML转换为JSON数组?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除