英文:
How to iterate through json file in Java
问题
在我的 Json 文件中,我有以下字段:
"categories": [{
"name1": "Corporate",
"parent": {
"name_parent": "PlanType1"
}
}],
在我的 Java 文件中,我有以下代码来访问该 json 变量:
PlanType.getnewEntity().getCategories()
.getCategories()
正在访问 categories
json 变量,我只是在通过 categories
进行迭代方面遇到了问题。
在我的代码中,我需要这样的逻辑:如果在 categories
中 name_parent = "PlanType1"
并且 name1 = "Corporate"
,则执行 x 操作。我只是在通过 json 进行迭代的过程中遇到了构建这个 if 语句的困难。
英文:
In my Json file I have the following field:
"categories": [{
"name1": "Corporate",
"parent": {
"name_parent": "PlanType1"
}
}],
In my Java file I have this code to access that json variable:
PlanType.getnewEntity().getCategories().
The .getCategories()
is accessing the "categories"
json variable, I just am having trouble iterating through "categories"
In my code I need the logic that if in "categories"
if name_parent = "PlanType1"
AND name1 = "Corporate"
do x. I am just having trouble constructing that if statement by iterating through the json.
答案1
得分: 1
你可以像下面这样进行迭代:
categories.getCategories().forEach(
category -> {
if("Corporate".equals(category.getName1()) &&
("PlanType1".equals(category.getParent().getNameParent()))) {
//执行逻辑
}
}
);
英文:
You can iterate like below
categories.getCategories().forEach(
category -> {
if("Corporate".equals(category.getName1()) &&
("PlanType1".equals(category.getParent().getNameParent()))) {
//do the logic
}
}
);
答案2
得分: 0
请试试这个。实际上,我不知道你获取的 JSON 变量是什么样的。但是,如果你将其转换为一个由 Map 组成的列表,它应该能够正常工作。例如:
List<Map<String, Object>> catogoriesList = (List<Map<String, Object>>) PlanType.getnewEntity().getCategories();
然后,你可以按照以下方式进行迭代:
for(Map<String, Object> catogory : catogoriesList){
Map<String, Object> parent = (Map<String, Object>) catogory.get("parent");
if(catogory.get("name1").toString().equals("Corporate") && parent.get("name_parent").toString().equals("PlanType1")){
// 在这里执行操作 x
}
}
英文:
Try this. I don't actually know how the JSON variable you are getting. But it would work if u cast it into a List of Maps. For example
List<Map<String, Object>> catogoriesList = (List<Map<String, Object>>) PlanType.getnewEntity().getCategories();
Then you'll be able to iterate through it like as follows.
for(Map<String, Object> catogory : catogoriesList){
Map<String, Object> parent = (Map<String, Object>) catogory.get("parent");
if(catogory.get("name1").toString().equals("Corporate") && parent.get("name_parent").toString().equals("PlanType1")){
// Do x here
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论