不使用GSON。
如果 myFilterObj 对象中的“chore”数组中有匹配的值,我将尝试从“chores”数组中提取文本值。
{
"chores": [
{
"text": "Wash the car",
"value": 1
},
{
"text": "Mow the lawn",
"value": 2
},
{
"text": "Vaccumm the floor",
"value": 3
},
{
"text": "Walk the dog",
"value": 4
}
],
"myFilterObj": {
"chore": [
1,
2
]
}
}
我做的第一件事就是将它们转换为 ArrayList。
下面是两个ArrayList。我的目标是打印第一个 ArrayList 中的文本(如果该值位于第二个 ArrayList 中)。
例如:洗车和吸尘地板应该打印输出,因为 1 和 2 在第二个 ArrayList 中,而 1 和 2 是第一个 ArrayList 中的值。
这是我到目前为止所拥有的。我一直在尝试将 allChores.value 与 value 进行比较。我想我应该使用removeAll或包含??
JSONArray allChores = data.getJSONArray("chores");
JSONArray myChores = myFilterObj.getJSONArray("chore");
ArrayList<Object> listdata1 = new ArrayList<Object>();
ArrayList<Object> listdata2 = new ArrayList<Object>();
if (allChores != null) {
for (int i = 0; i < allChores.length(); i++) {
//Adding each element of JSON array into ArrayList
listdata1.add(allChores.get(i));
}
}
if (myChores != null) {
for (int i = 0; i < myChores.length(); i++) {
//Adding each element of JSON array into ArrayList
listdata2.add(myChores.get(i));
}
}
//comapare allChores.value to myChores(value)
//printout allChores.text on match
[
{
"text":"Wash the car",
"value":1
},
{
"text":"Mow the lawn",
"value":7
},
{
"text":"Vaccumm the floor",
"value":2
},
{
"text":"Walk the dog",
"value":8
}
]
[
1,
2,
3
]
您可以使用 .filter 方法来实现此目的:
choresArray.filter((chore) => choreIdArray.includes(chore.value))
这将返回数组中的杂务列表,
那么如果你只想要标签,你可以使用 .map
results.map(res => res.label)
这将返回一个字符串数组。
您没有回答 Abra 关于是否使用 GSON 的问题,但是 我假设您确实使用 GSON,并在事实证明您不使用 GSON 时调整答案。
我首先将输入转换为 POJO。为此,我将为输入中的每个对象引入一个单独的记录
Chore
、McChores
和 Input
本身。
record Chore(int value, String text) {
}
record MyChores(List<Integer> chore) {
}
record Input(List<Chore> chores, MyChores myFilterObj) {
}
这样您就可以创建家务查找地图
public static void main(String[] args) {
final var data = """
{
"chores": [
{
"text": "Wash the car",
"value": 1
},
{
"text": "Mow the lawn",
"value": 2
},
{
"text": "Vaccumm the floor",
"value": 3
},
{
"text": "Walk the dog",
"value": 4
}
],
"myFilterObj": {
"chore": [
1,
2,
7
]
}
}
""";
final var input = new Gson().fromJson(data, Input.class);
final Map<Integer, String> choresLookup = input.chores().stream()
.collect(Collectors.toMap(Chore::value, Chore::text));
final var myChores = input.myFilterObj().chore().stream()
.filter(choresLookup::containsKey) // absent values gets filtered out
.map(choresLookup::get)
.toList();
}
结果
[Wash the car, Mow the lawn]