如何在结构上修改JsonObject并替换它的一些值?

时间:2018-02-13 14:42:00

标签: java android json gson

我在JsonObject中有一个json,例如:

"customer": {    
     "full_name": "John John",  
      "personal": {  
        "is_active": "1",    
        "identifier_info": {  
            "hobbies": [  
                "skiing",
                "traveling"
             ],  
             "user_id": "1234",  
             "office_id": "2345"
         }  
     }  
} 

有没有办法修改JsonObject,以便从hobbies完全删除identifier_info并保持其余部分不变,然后添加hobbies的内容和其他人一样吗?即

"customer": {    
     "full_name": "John John",  
      "personal": {  
        "is_active": "1",    
        "identifier_info": {  
            "skiing":"expert",
            "traveling":"rarely",
             "user_id": "1234",  
             "office_id": "2345"                                                                                  
         }
     }
}  

2 个答案:

答案 0 :(得分:3)

找到删除JSON数组“爱好”的完整实现,并直接将它们插入到父JSON对象中。

  public class ProcessJSONString {

  String data ="{\"customer\": {    \n" +
        "     \"full_name\": \"John John\",  \n" +
        "      \"personal\": {  \n" +
        "        \"is_active\": \"1\",    \n" +
        "        \"identifier_info\": {  \n" +
        "            \"hobbies\": [  \n" +
        "                \"skiing\",\n" +
        "                \"traveling\"\n" +
        "             ],  \n" +
        "             \"user_id\": \"1234\",  \n" +
        "             \"office_id\": \"2345\"\n" +
        "         }  \n" +
        "     }  \n" +
        "}} ";

public void processData() {
    try {
        JSONObject result = new JSONObject(data);
        JSONObject customer = result.getJSONObject("customer");
        JSONObject personal = customer.getJSONObject("personal");
        JSONObject identifierInfo = 
        personal.getJSONObject("identifier_info");
        JSONArray hobbies = identifierInfo.getJSONArray("hobbies");

        identifierInfo.remove("hobbies");

         //Under the assumption the tags will be added by the user, the code has been inserted.
        identifierInfo.put("skiing","expert");
        identifierInfo.put("traveling","rarely");



    } catch (JSONException e) {
        e.printStackTrace();
    }

}

public static void main(String[] args) {
    ProcessJSONString instance = new ProcessJSONString();
    instance.processData();
}
}

答案 1 :(得分:1)

使用JsonObject的{​​{3}}方法应该没问题。它返回已删除的JsonElement。假设原始json是一个名为customer的JsonObject:

JsonObject identifierInfo = customer.getAsJsonObject("personal").getAsJsonObject("identifier_info");
JsonArray hobbies = (JsonArray) identifierInfo.remove("hobbies");

之后你可以将兴趣爱好添加到identifierInfo并获得所需的结果:

for (JsonElement aHobby : hobbies) {
    identifierInfo.addProperty(aHobby.getAsString(), "expert");
}

不要忘记根据需要添加空检查。