2017-09-14 32 views
1

我正在使用JsonPath從JSON文件中檢索值。 JSON文件看起來是這樣的:從JSONArray獲取元素時保留雙引號

[ 
    { 
    "username": "John", 
    "password": { 
     "passwordValue": "passwordjohn", 
     "secret_key": "123" 
    } 
    }, 
    { 
    "username": "Nick", 
    "password": { 
     "passwordValue": "XXX", 
     "secret_key": "ZZZ", 
     "other_key": "YYY" 
    } 
    } 
] 

的JsonPath我使用的是從一個特定的用戶檢索password。例如:

fun getPassword() { 
    val passwords: JSONArray = read(jsonFile, "\$.[?(@.name==\"John\")].password") 
} 

但是,我發現了兩個障礙。首先,我始終得到net.minidev.json.JSONArray,並且附加[0]的相同路徑不起作用。

因此,我嘗試從JSONArray中獲得唯一的元素,例如:credentials[0]。不幸的是,這刪除在字段名的雙引號,導致這樣的事情:

{passwordValue: passwordjohn, secret_key: 123} 

這是不可能的工作。

我正在尋找一種方式來獲得這種回:

{"passwordValue": "passwordjohn", "secret_key": "123"} 
+1

有趣的是,大多數過去的問題都會問如何刪除引號:) – notyou

+0

檢查此github問題: https://github.com/json-path/JsonPath/issues/275#issue-184313633 – pRaNaY

回答

0

我最終什麼事做的是將其轉換爲String後刪除從JSONArray開始的[]符號:

private fun JSONArray.toCredentialString(): String { 
    val credentialString = this.toString() 
    return credentialString.substring(1, credentialString.length - 1) 
} 

歡迎任何更好的解決方案。