使用gson

时间:2016-04-18 08:00:03

标签: java json gson

我正在探索gson并想检查是否可以删除和添加元素。我有以下json

{
  "header": {
"timeStamp": "2016-02-09T15:22:36.107-08:00",
"uniqueid": "321ef660",
},
"body": {
"search": {
  "searchId": 9206422282,
      "DateFrom": "2016-04-15T00:00:00-07:00",
      "DateTo": "2016-06-24T00:00:00-07:00"
    }
  },
  "amount": [
    {   
        "amount": 73.704285,
        "currency": "USD"
      },
      "amountagain": {
        "amount": 96.791435,
        "currency": "USD"
      },
      "winners": null,
      "pgoodId": null,
      },

现在我想在body下面添加一个新元素:

{
"header": {
"timeStamp": "2016-02-09T15:22:36.107-08:00",
"uniqueid": "321c5690-1d2e-4403-9c31-029cc47ef660",
},
"body": {
"search": {
  "searchId": 9206422282,
      "DateFrom": "2016-04-15T00:00:00-07:00",
      "DateTo": "2016-06-24T00:00:00-07:00"
      "AddANewFieldHere" : **"2016-04-18"**
    }
  }

当我做的时候

JsonObject jsonObject = new JsonObject();
    try {
        JsonParser parser = new JsonParser();
        JsonElement jsonElement = parser.parse(new FileReader("src/main/resources/search.json"));
        jsonObject = jsonElement.getAsJsonObject();
    } catch (FileNotFoundException e) {

    } catch (IOException ioe){

    }

//    jsonObject.get("checkin");
jsonObject.addProperty("AddANewFieldHere","2016-04-18");
    System.out.print(jsonObject);

}

它在文档的末尾添加了这个属性,而不像我期望的那样。

1 个答案:

答案 0 :(得分:2)

<?php echo '<form method="post" action="index.php">'; for($i=0;$i<4;$i++){ echo 'Male <input type="radio" name="gender' . $i . '" value="Male">Female <input type="radio" name="gender' . $i . '" value="Female"><br>'; } echo '<input type="submit" value="submit" name="test"></form> ?> 是根节点。您需要导航到要修改的节点。

jsonObject

从示例输出看,它看起来想要它在路径JsonObject body = jsonObject.getAsJsonObject("body"); body.addProperty("AddANewFieldHere","2016-04-18"); 下而不是body/search/searchId但是:

body