无法在groovy中解析json

时间:2018-06-02 14:26:36

标签: groovy

import groovy.json.JsonSlurper 

def json ='{"icons":{},"id":"template1","name":"template1","canDelete":true,"category":"Custom","defaultHostedQueue":null,"description":"","template":{"options":[{"enabled":true,"definition":{"id":"5d58cc01-7c75-450c-be18-a388ddb129ec"},"inputs":{"branchFilters":"[\"+refs/heads/*\"]","additionalFields":"{}"}},{"enabled":false,"definition":{"id":"a9db38f9-9fdc-478c-b0f9-464221e58316"},"inputs":{"workItemType":"826148","assignToRequestor":"true","additionalFields":"{}"}}],"variables":{"system.debug":{"value":"false","allowOverride":true}},"retentionRules":[{"branches":["+refs/heads/*"],"artifacts":[],"artifactTypesToDelete":["FilePath","SymbolStore"],"daysToKeep":10,"minimumToKeep":1,"deleteBuildRecord":true,"deleteTestResults":true}],"properties":{},"tags":[],"_links":{"self":{"href":"https://abc.visualstudio.com/_apis/build/Definitions/2?revision=1"},"web":{"href":"https://abc.visualstudio.com/00000000-0000-0000-0000-000000000000/_build/definition?definitionId=2"},"editor":{"href":"https://abc.visualstudio.com/00000000-0000-0000-0000-000000000000/_build/designer?id=2&_a=edit-build-definition"},"badge":{"href":"https://abc.visualstudio.com/_apis/public/build/definitions/00000000-0000-0000-0000-000000000000/2/badge"}},"buildNumberFormat":"$(date:yyyyMMdd)$(rev:.r)","jobAuthorizationScope":"projectCollection","jobTimeoutInMinutes":60,"jobCancelTimeoutInMinutes":5,"process":{"phases":[{"steps":[{"environment":{},"enabled":true,"continueOnError":false,"alwaysRun":false,"displayName":"gradlew build","timeoutInMinutes":0,"task":{"id":"8d8eebd8-2b94-4c97-85af-839254cc6da4","versionSpec":"2.*","definitionType":"task"},"inputs":{"wrapperScript":"$(Parameters.wrapperScript)","cwd":"","options":"","tasks":"$(Parameters.tasks)","publishJUnitResults":"true","testResultsFiles":"**/build/test-results/TEST-*.xml","testRunTitle":"","codeCoverageTool":"None","classFilesDirectories":"build/classes/main/","classFilter":"","failIfCoverageEmpty":"false","javaHomeSelection":"JDKVersion","jdkVersion":"default","jdkUserInputPath":"","jdkArchitecture":"x64","gradleOpts":"-Xmx1024m","sqAnalysisEnabled":"false","sqGradlePluginVersionChoice":"specify","sqGradlePluginVersion":"2.6.1","checkstyleAnalysisEnabled":"false","findbugsAnalysisEnabled":"false","pmdAnalysisEnabled":"false"}},{"environment":{},"enabled":true,"continueOnError":false,"alwaysRun":false,"displayName":"Copy Files to: $(build.artifactstagingdirectory)","timeoutInMinutes":0,"task":{"id":"5bfb729a-a7c8-4a78-a7c3-8d717bb7c13c","versionSpec":"2.*","definitionType":"task"},"inputs":{"SourceFolder":"$(system.defaultworkingdirectory)","Contents":"**/*.jar","TargetFolder":"$(build.artifactstagingdirectory)","CleanTargetFolder":"false","OverWrite":"false","flattenFolders":"false"}},{"environment":{},"enabled":true,"continueOnError":false,"alwaysRun":false,"displayName":"Publish Artifact: drop","timeoutInMinutes":0,"task":{"id":"2ff763a7-ce83-4e1f-bc89-0ae63477cebe","versionSpec":"1.*","definitionType":"task"},"inputs":{"PathtoPublish":"$(build.artifactstagingdirectory)","ArtifactName":"drop","ArtifactType":"Container","TargetPath":"","Parallel":"false","ParallelCount":"8"}}],"name":"Phase 1","refName":"Phase_1","condition":"succeeded()","target":{"executionOptions":{"type":0},"allowScriptsAuthAccessOption":false,"type":1},"jobAuthorizationScope":"projectCollection","jobCancelTimeoutInMinutes":1}],"type":1},"repository":{"properties":{"labelSources":"0","labelSourcesFormat":"$(build.buildNumber)","reportBuildStatus":"true","fetchDepth":"0"},"id":"c96c9c65-5403-40f7-843e-791fd085e6ce","type":"TfsGit","name":"Test","url":"https://abc.visualstudio.com/DealerPad/_git/Test","defaultBranch":"refs/heads/master","clean":null,"checkoutSubmodules":false},"processParameters":{"inputs":[{"aliases":[],"options":{},"properties":{},"name":"wrapperScript","label":"Gradle wrapper","defaultValue":"gradlew","required":true,"type":"filePath","helpMarkDown":"Relative path from the repository root to the Gradle Wrapper script.","visibleRule":"","groupName":""},{"aliases":[],"options":{},"properties":{},"name":"tasks","label":"Tasks","defaultValue":"build","required":true,"type":"string","helpMarkDown":"","visibleRule":"","groupName":""}]},"quality":"definition","drafts":[],"queue":{"_links":{"self":{"href":"https://abc.visualstudio.com/_apis/build/Queues/14"}},"id":14,"name":"Hosted VS2017","url":"https://abc.visualstudio.com/_apis/build/Queues/14","pool":{"id":4,"name":"Hosted VS2017","isHosted":true}},"id":2,"name":"TypeHierarchy-Gradle-CI","url":"https://abc.visualstudio.com/_apis/build/Definitions/2?revision=1","uri":"vstfs:///Build/Definition/2","path":"\\","type":"build","queueStatus":"enabled","revision":1,"createdDate":"2018-05-28T17:02:43.12Z","project":{"name":"","state":"unchanged","visibility":"unchanged"}}}'

def parser = new JsonSlurper()
def jsonResp = parser.parseText(json)
println jsonResp

错误:

groovy.json.JsonException: expecting '}' or ',' but got current char '+' with an int value of 43

The current character read is '+' with an int value of 43
expecting '}' or ',' but got current char '+' with an int value of 43
line number 1
index number 255

让我们指出问题:

import groovy.json.JsonSlurper 

def json ='''
{
    "branchFilters": "[\"+refs/heads/*\"]"
}
'''

def parser = new JsonSlurper()
def jsonResp = parser.parseText(json)
println jsonResp

错误:

groovy.json.JsonException: expecting '}' or ',' but got current char '+' with an int value of 43

The current character read is '+' with an int value of 43
expecting '}' or ',' but got current char '+' with an int value of 43
line number 3
index number 27

2 个答案:

答案 0 :(得分:5)

您可以使用不需要转义反斜杠的所谓美元斜线字符串

import groovy.json.JsonSlurper 
def json = $/
{
    "branchFilters": "[\"+refs/heads/*\"]"
}
/$
println json

def parser = new JsonSlurper()
def jsonResp = parser.parseText(json)
println jsonResp

答案 1 :(得分:0)

尝试println变量json,你会发现两个反斜杠都消失了,这导致了一个无效的JSON字符串:  {“branchFilters”:“[”+ refs / heads / *“]”}

如果需要将JSON字符串直接粘贴到代码中,则必须转义每个反斜杠。如果从其他来源(如文件或http请求)获取String,则不适用。

import groovy.json.JsonSlurper 

def json ='''
{
    "branchFilters": "[\\"+refs/heads/*\\"]"
}
'''
println json // "branchFilters": "[\"+refs/heads/*\"]"
def parser = new JsonSlurper()
def jsonResp = parser.parseText(json)
println jsonResp // [branchFilters:["+refs/heads/*"]]