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

时间:2018-10-09 08:29:57

标签: java json gson

我希望删除JSON对象的一部分,此刻我似乎只能返回整个对象。

JSON格式:

{"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"}

我希望删除JSON的[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);

这将输出以下JSON:

{"blobJson":"","deviceMfg":-1,"eventCode":-1,"sensorClass":-1,"sensorUUID":"","timeStamp":0.0,"uID":"_-1_-1"}

2 个答案:

答案 0 :(得分:0)

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);

这里“ Yourpojoclass”将是您的包含字符串字段参数的类:

现在将您的frameData值设置为null,并使pojo类@JsonInclude(value = Include.NON_NULL)

,然后再次将其转换为json。

答案 1 :(得分:0)

如果要从字符串中删除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 String。