我需要根据它的关联名称找到一个 Id。我的程序对 API 进行 REST 调用。API 以 JSON 格式返回结果。Name 是唯一的,所以我想用它来获取它的 Id 值。请注意 ... 可以包含任何内容,并且确实包含一些 {Such}Id 键。Id 可以嵌套在任意数量的 {...{...{...}...}...} 中,Id 总是紧接在名称之前。
注意:...是出于隐私原因无法显示的代码。代码本身(在排除私有数据之前)是由 Advanced Rest Client 返回并在http://jsonlint.com/上验证为有效 JSON 的 REST 调用的结果。
代码返回如下:
{
Id: "d5a94d1a-afb7-4e1d-ae0d-a22e01393666"
ProjectId: "ed61c45a-f208-4115-8584-a21a00c51ac0"
Name: "Automated Runs"
OrderNumber: 0
Expands: [3]
0: "Children"
1: "Parent"
2: "Project"
...
scripts: [4]
0: {
Id: "0b70a55c-5e68-4b27-bfcf-a22f00c5dc48"
Name: "3816"
PackageId: "d5a94d1a-afb7-4e1d-ae0d-a22e01393666"
ProjectId: "ed61c45a-f208-4115-8584-a21a00c51ac0"
...
Expands: [6]
0: "Assignments"
1: "Attachments"
2: "FieldControls"
3: "FieldValues"
4: "Package"
5: "Steps"
...
1: {
Id: "14e5c663-0d5a-46bb-ac48-a22f00c15998"
Name: "3814"
PackageId: "d5a94d1a-afb7-4e1d-ae0d-a22e01393666"
ProjectId: "ed61c45a-f208-4115-8584-a21a00c51ac0"
...
Expands: [6]
0: "Assignments"
1: "Attachments"
2: "FieldControls"
3: "FieldValues"
4: "Package"
5: "Steps"
...
2: {
Id: "00d52fcd-b611-4f69-aeb6-a22f00c263a9"
Name: "3815"
ProjectId: "ed61c45a-f208-4115-8584-a21a00c51ac0"
...
Expands: [6]
0: "Assignments"
1: "Attachments"
2: "FieldControls"
3: "FieldValues"
4: "Package"
5: "Steps"
...
3: {
Id: "4d3a6132-8497-4b6b-a064-a22f00c669ff"
Name: "3817"
...
Expands: [6]
0: "Assignments"
1: "Attachments"
2: "FieldControls"
3: "FieldValues"
4: "Package"
5: "Steps"
...
}
我尝试过的事情包括正则表达式(我是新手并且遇到了一些麻烦)和简单的字符串拆分。虽然我有字符串拆分工作,但它是半硬编码的。
我想要的是这样的:
def getID(myJSON:String, myName:String){
val pattern = "\"Id\": \"*\",\r\n\"Name\":\"" + myName + "\",\""
get the id (*) from result using pattern
}
或者甚至更好地将其转换为通用的。
def getID(myJSON:String, myValue:String, searchKey:String, findKey:String){
val pattern = { ... findKey: *...} in the inner most { ... searchKey: * ...} scope
get the id (*) from result using the pattern in the found {...searchKey...} scope
}
两者都很棒,非常感谢。我当前的代码如下所示:
result.split("Id\": \"")(3).split("\"")(0)
它可能很漂亮,但它有很多不幸的空间。一个 Id 可能由用户创建,它将计数设置为不正确,等等......
谢谢你,埃里克·斯通