紫风幻雪 2017-11-29 02:24 采纳率: 7.1%
浏览 2710
已采纳

Android json字符串替换value值的问题

JSON字符串如下:{"device_id": "gh_4da91c444fee_8c04d0b766780c62","device_type":"gh_4da91c444fee","msg_type":"notify","data":"jlfjsdlkjflk","services":{"operation_status":{"status": 0},"lightbulb":{"alpha":70}}}我先替换status和alpha的值, 但是每一次更换的值是不固定的,你有什么方法可以替换吗

  • 写回答

3条回答 默认 最新

  • 衫燃愚下 2017-11-29 06:00
    关注

    你可以用fastjson,将json字符串转成对象,然后进行数值替换
    json对象,在java中其实就是map

         public void test(){
            /*
            {
                "device_id": "gh_4da91c444fee_8c04d0b766780c62",
                "device_type": "gh_4da91c444fee",
                "msg_type": "notify",
                "data": "jlfjsdlkjflk",
                "services": {
                    "operation_status": {
                        "status": 0
                    },
                    "lightbulb": {
                        "alpha": 70
                    }
                }
            }
             */
            String jsonStr = "";
                    //转换成JSON对象
            JSONObject jsonObj = JSONObject.parseObject(jsonStr);
                    //根据key获取对象
            JSONObject services = jsonObj.getJSONObject("services");
    
            JSONObject operation_status = services.getJSONObject("operation_status");
            operation_status.put("status", 1);
    
            JSONObject lightbulb = services.getJSONObject("lightbulb");
            lightbulb.put("alpha", 100);
    
            jsonStr = jsonObj.toJSONString();
    
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?