Java 使用 Gson 将 XML 文件转换为 Json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27648774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:47:08  来源:igfitidea点击:

Convert an XML file to Json using using Gson

javaxmljson

提问by phoenix

I found that many of the tutorials on the net and here on SO also refer to net.sf.jsonlibrary to convert an xml file to json object.

我发现网上和 SO 上的许多教程也提到net.sf.json了将 xml 文件转换为 json 对象的库。

But, I want an alternative preferably using Gson. Is it possible? I don't have well defined Java Classes for the XML file. But, I just want to convert the xml file to com.google.gson.JsonObject. How to achieve it?

但是,我想要一个最好使用 Gson 的替代方案。是否可以?我没有为 XML 文件定义明确的 Java 类。但是,我只想将 xml 文件转换为com.google.gson.JsonObject. 如何实现?

采纳答案by Michallis

I've done the same using JAXB to convert my xml to an object, and passing the object to gson. I know it takes one additional step, but that worked convenient for me. Upon converting xml to jaxb see also: Use JAXB to create Object from XML String

我已经使用 JAXB 将我的 xml 转换为一个对象,并将该对象传递给 gson。我知道这需要一个额外的步骤,但这对我来说很方便。将 xml 转换为 jaxb 时,另请参阅: 使用 JAXB 从 XML 字符串创建对象