繁体   English   中英

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

[英]GSON - remove JSON data from JSON object

我正在寻找删除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"}

我正在寻找删除[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] 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"}
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。

如果要从字符串中删除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", "[]");

您可以使用来自com.fasterxml.jackson.databind ObjectMapper ,但是随后您还需要具有与json键对应的所有成员变量的对应类。 在上述方法中,您可以直接操作Json String。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM