2017-01-23 69 views
0

我試圖從下面的JSON文本中設置作者值,但是我的代碼正在刪除json文本的所有其他子節點。設置特定的JSONPATH元素值

{ 
    "store": { 
     "book": [ 
      { 
       "category": "reference", 
       "author": "XXXXXXXXXXXXXXXXX", 
       "title": "Sayings of the Century", 
       "price": 8.95 
      }, 
      { 
       "category": "fiction", 
       "author": "Evelyn Waugh", 
       "title": "Sword of Honour", 
       "price": XXXXXXXXXXXXXXXXXXXXX 
      }, 
      { 
       "category": "fiction", 
       "author": "Herman Melville", 
       "title": "Moby Dick", 
       "isbn": "0-553-21311-3", 
       "price": 8.99 
      }, 
      { 
       "category": "fiction", 
       "author": "J. R. R. Tolkien", 
       "title": "The Lord of the Rings", 
       "isbn": "0-395-19395-8", 
       "price": 22.99 
      } 
     ], 
     "bicycle": { 
      "color": "red", 
      "price": 19.95 
     } 
    }, 
    "expensive": 10 
} 

我試圖將第一本書中的作者更新爲其他值,如下所示。

Object updatedJson = JsonPath.using(configuration).parse(jsonInput).json(); 
String jayPath = "$..book[0].author"; 
String tagValue = "ReplacedText"; 
       String jsonToParse = updatedJson.toString(); 
       updatedJson = JsonPath.parse(jsonToParse).set(jayPath, tagValue).json(); 

經過設置步驟我的json只有像下面的書[1]的內容。請告訴我如何才能得到我用替換值作爲輸出給出的整個json輸入。

{store={book=[{"category"=reference, author=XXXXXXXXXXXXXXXXX, title=Sayings of the Century, price=8.95} 

Regards, Sathish。

回答

0

工作正常,無需轉換DocumentContext爲JSON

public static void main(String[] args) { 
    DocumentContext json = JsonPath.using(configuration).parse(jsonInput); 
    String jayPath = "$..book[0].author"; 
    String tagValue = "ReplacedText"; 
    System.out.println(json.set(jayPath, tagValue).jsonString()); 
} 
+0

,您好:感謝您的回答!我意識到我現在做了什麼錯誤。現在它爲我工作。 – user741699