代码之家  ›  专栏  ›  技术社区  ›  Srinivasan Ramu

如何使用json路径从json字符串中获取json节点值?

  •  0
  • Srinivasan Ramu  · 技术社区  · 7 年前

    下面是我的 JSON 文件

    {
      "squadName": "Super hero squad",
      "homeTown": "Metro City",
      "formed": 2016,
      "secretBase": "Super tower",
      "active": true,
      "members": [
        {
          "name": "Molecule Man",
          "age": 29,
          "secretIdentity": "Dan Jukes",
          "powers": [
            "Radiation resistance",
            "Turning tiny",
            "Radiation blast"
          ]
        },
        {
          "name": "Madame Uppercut",
          "age": 39,
          "secretIdentity": "Jane Wilson",
          "powers": [
            "Million tonne punch",
            "Damage resistance",
            "Superhuman reflexes"
          ]
        },
        {
          "name": "Eternal Flame",
          "age": 1000000,
          "secretIdentity": "Unknown",
          "powers": [
            "Immortality",
            "Heat Immunity",
            "Inferno",
            "Teleportation",
            "Interdimensional travel"
          ]
        }
      ]
    }
    

    检索所有成员名称的JSON路径是-$。成员[*]。名称

    我使用Ready API和Groovy脚本使用上述路径读取此json,但我遇到一条错误消息 java.lang.NoClassDefFoundError: Could not initialize class net.minidev.json.JSONValue 当我执行下面的代码时

    import com.jayway.jsonpath.*
    
    Object dataObject = JsonPath.parse(jsonmentionedabove).read(
    '$.members[*].name')
    

    我有以下几点 jars 在我的Ready API库中(&A);ext文件夹,并在我的电脑上安装java 9.0.1版

    json-path-2.4.0, json-smart-2.3
    

    你能告诉我是什么导致了这个问题吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Matias Bjarland    7 年前

    我不熟悉Ready API或json路径和json智能库,但使用纯groovy,您可以:

    import groovy.json.*
    
    def str  = """<the json string in your question>"""
    def json = new JsonSlurper().parseText(str)
    def memberNames = json.members*.name
    
    println memberNames.join(", ")
    

    执行时将打印:

    Molecule Man, Madame Uppercut, Eternal Flame
    

    JsonSlurper返回一个java。util。可以使用普通groovy导航的地图结构的地图 findAll ,则, collect ,etc操作或 spead operator ( *. )如上所述。

        2
  •  0
  •   Srinivasan Ramu    7 年前

    放置asm-1.0.2。Ready API lib文件夹中的jar文件解决了该问题。