代码之家  ›  专栏  ›  技术社区  ›  Colin747

GSON-从JSON对象中删除JSON数据

  •  0
  • Colin747  · 技术社区  · 6 年前

    {"blobJson":"{\"sensorID\":\"111122\",\"width\":32,\"height\":31,\"frameData\":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}","deviceMfg":2,"eventCode":101,"sensorClass":1,"sensorUUID":"111122","timeStamp":1.53907307310099994E18,"uID":"111122_1_2"}
    

    我想把它移走 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

    目前我正在使用以下代码:

        JsonParser jp = new JsonParser(); //from gson
        JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); 
        JsonObject rootobj = root.getAsJsonObject();
        System.out.println(rootobj);
    

    {"blobJson":"","deviceMfg":-1,"eventCode":-1,"sensorClass":-1,"sensorUUID":"","timeStamp":0.0,"uID":"_-1_-1"}
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   YK S    6 年前

    如果要删除 framedata key and value 从弦上。你可以用 org.json.JSONObject 如下图所示:

    JSONObject jo1 = new JSONObject("{\"blobJson\":{\"sensorID\":\"111122\",\"width\":32,\"height\":31,\"frameData\":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},\"deviceMfg\":2,\"eventCode\":101,\"sensorClass\":1,\"sensorUUID\":\"111122\",\"timeStamp\":1.53907307310099994E18,\"uID\":\"111122_1_2\"}");
    jo1.getJSONObject("blobJson").remove("frameData");
    

    key framedata 但我只想要 value [] 然后执行以下操作:

    JSONObject jo1 = new JSONObject("{\"blobJson\":{\"sensorID\":\"111122\",\"width\":32,\"height\":31,\"frameData\":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},\"deviceMfg\":2,\"eventCode\":101,\"sensorClass\":1,\"sensorUUID\":\"111122\",\"timeStamp\":1.53907307310099994E18,\"uID\":\"111122_1_2\"}");
    jo1.getJSONObject("blobJson").put("frameData", "[]");
    

    你可以用 ObjectMapper com.fasterxml.jackson.databind 但是您还需要相应的类以及与json键对应的所有成员变量。在上述方法中,您可以直接操作Json字符串。

        2
  •  0
  •   GauravRai1512    6 年前
    String stringifyRequest="{"blobJson":"{\"sensorID\":\"111122\",\"width\":32,\"height\":31,\"frameData\":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}","deviceMfg":2,"eventCode":101,"sensorClass":1,"sensorUUID":"111122","timeStamp":1.53907307310099994E18,"uID":"111122_1_2"}";
    
     final ObjectMapper mapper = new ObjectMapper();
            "Yourpojoclass" investmentResponse = mapper.readValue(stringifyRequest, "Yourpojoclass".class);
    

    现在将frameData值设置为null,并使pojo类@JsonInclude(value=Include.NON\u为null)