【问题标题】:All element names and values in a JSONJSON 中的所有元素名称和值
【发布时间】:2018-02-11 14:12:59
【问题描述】:

我正在尝试从 JSON 中获取所有元素名称和值。 基本上,我将得到一个 JSON 响应,并且需要将它与 XML 响应进行比较。我现在决定的方法是从 JSON 和 XML 中获取所有元素名称和值,然后将它们存储在单独的列表中。最后,我将比较列表。

第一季度。有没有更好的方法来做我计划的事情? (比较 JSON 和 XML)

如果没有, 这样做时我遇到了一些麻烦。我的 JSON 是一个嵌套的 JSON,我需要获取所有元素的值及其名称。但是,使用 JSON,我只能获得最外层的元素。我需要这个获取是动态的,因为我想稍后将相同的代码重新用于其他类似的比较

(Using a sample XML I found in another answer on StackOverflow)

import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
import groovy.json.JsonBuilder;
import java. util.ArrayList;
import java. util.Iterator
import groovy.json.JsonSlurper

xml = """
{
"master": {
   "node": "xyz", 
   "files": [{"type": "modified", "file": "test.txt"}]
   }, 
"testbranch2": {
   "node": "abc", 
   "files": [{"type": "modified", "file": "test.txt"}] 
   }, 
"testbranch": {
   "node": "xxx", 
   "files": [{"type": "modified", "file": "test.txt"}], 
   }
}
"""

def json = new JSONObject(xml);
def test = new JsonSlurper().parseText(json.toString())
log.info test.keySet() 
log.info test.Outer.keySet()

json.keys() 只设法获得最外层的密钥,而不是全部。

提前致谢!

【问题讨论】:

    标签: java json xml comparison


    【解决方案1】:

    您可以使用 jackson 将 xml 转换为 json / JsonNode,然后轻松地与您想要的任何级别进行比较。

    请参阅下面的链接以了解如何将 xml 转换为 json。 How to convert XML to JSON using only Jackson?

    【讨论】:

      猜你喜欢
      • 2011-05-15
      • 2023-03-10
      • 1970-01-01
      • 2021-12-30
      • 2021-03-11
      • 1970-01-01
      • 2019-01-06
      • 2019-05-29
      相关资源
      最近更新 更多