从JSONArray(Java)中删除可重复的值

时间:2018-06-29 10:34:01

标签: java json

我有一个JSON数组,如下所示,它带有多个带有两个键的JSON对象:

1)Submitted_datetime

2)值

  

我需要删除其值重复的那些JSON对象,并保持   只有最新值。

我想保留重复的值,但不要连续重复相同的值。

我必须使用Java语言来做!!

有什么想法吗?预先感谢

示例JSON

[{
        "submitted_datetime": "2018-06-29 11:14:30",
        "value": 6
    }, {
        "submitted_datetime": "2018-06-29 11:16:20",
        "value": 6
    }, {
        "submitted_datetime": "2018-06-29 11:41:59",
        "value": 6
    }, {
        "submitted_datetime": "2018-06-29 11:43:49",
        "value": 2
    }, {
        "submitted_datetime": "2018-06-29 11:46:13",
        "value": 10
    }, {
        "submitted_datetime": "2018-06-29 11:46:42",
        "value": 10
    }, {
        "submitted_datetime": "2018-06-29 12:01:33",
        "value": 8
    }, {
        "submitted_datetime": "2018-06-29 12:02:28",
        "value": 8
    }, {
        "submitted_datetime": "2018-06-29 12:35:52",
        "value": 6
    }, {
        "submitted_datetime": "2018-06-29 12:35:53",
        "value": 8
    }
]

预期结果

[   {
        "submitted_datetime": "2018-06-29 11:41:59",
        "value": 6
    }, {
        "submitted_datetime": "2018-06-29 11:43:49",
        "value": 2
    }, {
        "submitted_datetime": "2018-06-29 11:46:42",
        "value": 10
    }, {
        "submitted_datetime": "2018-06-29 12:01:33",
        "value": 8
    }, {
        "submitted_datetime": "2018-06-29 12:35:52",
        "value": 6
    }, {
        "submitted_datetime": "2018-06-29 12:35:53",
        "value": 8
    }
]

1 个答案:

答案 0 :(得分:1)

如果您愿意使用Jackson(一种流行的Java JSON解析器),则可以创建一个类来将项目映射到:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Foo {

    @JsonProperty("submitted_datetime")
    private String submittedDateTime;

    private Integer value;

    // Getters and setters
}

然后将JSON数组作为列表读取:

ObjectMapper mapper = new ObjectMapper();
List<Foo> list = mapper.readValue(json, new TypeReference<List<Foo>>() {});

然后用您需要的物品构建一个新列表(我假设列表是有序的):

Foo previousItem = null;
List<Foo> filteredList = new ArrayList<>();

for (Iterator<Foo> iterator = list.iterator(); iterator.hasNext();) {

    Foo item = iterator.next();

    if (previousItem != null && !item.getValue().equals(previousItem.getValue())) {
        filteredList.add(previousItem);
    }

    if (!iterator.hasNext() && !item.getValue().equals(previousItem.getValue())) {
        filteredList.add(item);
    }

    previousItem = item;            
}

最后创建一个新的JSON:

String newJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(filteredList);

输出将是:

[ {
  "value" : 6,
  "submitted_datetime" : "2018-06-29 11:41:59"
}, {
  "value" : 2,
  "submitted_datetime" : "2018-06-29 11:43:49"
}, {
  "value" : 10,
  "submitted_datetime" : "2018-06-29 11:46:42"
}, {
  "value" : 8,
  "submitted_datetime" : "2018-06-29 12:02:28"
}, {
  "value" : 6,
  "submitted_datetime" : "2018-06-29 12:35:52"
}, {
  "value" : 8,
  "submitted_datetime" : "2018-06-29 12:35:53"
} ]