java - 如何从结构上修改 JsonObject 并替换其某些值?

标签 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,以便从identifier_info中完全删除hobbies并保留其余部分不变,然后添加hobbies的内容和其他的一样吗?即

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

最佳答案

找到删除 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();
}
}

关于java - 如何从结构上修改 JsonObject 并替换其某些值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48769351/

相关文章:

java - org.apache.tomcat.util.bcel.classfile.ClassFormatException : Invalid byte tag in constant pool: 15

android - 如何将包含在 Singlechildscrollview 中的列中的 Widget 居中?

json - 来自单列中嵌套字典的 Pandas 数据框

javascript - 如何从 json 渲染对象

java - 如何通过java以键值对的形式在android中添加复选框?

java - 使用 Tailer 和 WatchService

java - 只有一个单选按钮

android - SQL : Query() where COL = int instead of string ?(图片+里面的代码)

Android BitmapFactory 在 Base64 解码字节数组上返回 null

javascript - 通过引用特定属性名称从 Javascript JSON 对象获取值