java.lang.NumberFormatException:当尝试使用包含数字的路径读取 Json 时输入字符串

java.lang.NumberFormatException: For input string when trying to read Json with a path that contains number

我正在尝试 return 一个 JSON 数组,如下所示:

jsarr = new JSONArray(JSON.read(genericPathComp).toString());

其中 genericPathComp 是已编译的 JSON 路径。

这种方法工作正常,但是当我的 JSON 路径包含数字时,会抛出以下异常:

java.lang.NumberFormatException: For input string: "ustomerAccountBalance,billingAccount[(-1"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:492)
    at java.lang.Integer.parseInt(Integer.java:527)
    at com.jayway.jsonpath.internal.filter.ArrayIndexFilter.filter(ArrayIndexFilter.java:75)
    at com.jayway.jsonpath.internal.filter.PathTokenFilter.filter(PathTokenFilter.java:50)
    at com.jayway.jsonpath.JsonPath.read(JsonPath.java:255)
    at com.jayway.jsonpath.internal.JsonReader.read(JsonReader.java:103)
    at dataAnalytics.ValidateAttributes.responseParser(ValidateAttributes.java:174)
    at dataGeneration.Main.main(Main.java:76)

抛出这个异常的JSON路径是: $.parts[customerAccountBalance,billingAccount[-1:]]

我不明白为什么它要解析一个 int,我错过了什么?

编辑:我正在使用 jayway 解析器,变量 JSON 是一个 ReadContext 变量。所以它是有效 JSON 的句柄。到目前为止,此代码适用于每个 JSON 路径,其中没有数字。因此,例如 $.parts.billingAccount 和 $.name.date 都有效。

原来的 JSON 看起来像这样:

[
  {
    "Name": [
      {
        "value": "John"
      }
    ],
    "parts": {
      "customerAccountBalance": [
        {
          "amount": "1"
        }
      ],
      "billingAccount": [
        {
          "type": "example"
        },
        {
          "date": "also example"
        }
      ]
    }
  }
]

而且我想要 return 一个数组,其中包含最后一个结算帐户数组和所有客户帐户余额。

这个例外...

java.lang.NumberFormatException: For input string: "ustomerAccountBalance,billingAccount[(-1"
at 

... 发生是因为 Jayway 期望数字 (0 - 9) 跟在左方括号之后。查看 Jayway docs 它允许左方括号后跟 ' (对于括号标记的子项)或 ? (对于过滤器),除此之外它期望一个左方括号括号后跟一个数字。

因此,您问题中提供的 json 路径无效。我怀疑您正在尝试阅读 parts.customerAccountBalance 中的最后一个 billingAccount。如果是这样,请继续阅读 ...

鉴于此 JSON:

{
  "parts": {
    "customerAccountBalance": {
      "billingAccount": [
        1,
        2,
        3
      ]
    }
  }
}

此 json 路径:$.parts.customerAccountBalance.billingAccount[-1:] 将 return:

[
   3
]

您可以使用在线 Jayway Evaluator.

自行尝试

更新 回复:

And I would like to return an array that consists of the that last array of billing account and all of customer account balance.

鉴于此 JSON:

{
  "Name": [
    {
      "value": "John"
    }
  ],
  "parts": {
    "customerAccountBalance": [
      {
        "amount": "1"
      }
    ]
  },
  "billingAccount": [
    {
      "type": "example"
    },
    {
      "date": "also example"
    }
  ]
}

这涉及两个读取调用:

  • “结算帐户的最后一个数组”:$.billingAccount[-1:]
  • “所有客户账户余额”:$.parts.customerAccountBalance