Parsing json

Fermé
gloria5739 Messages postés 49 Date d'inscription lundi 21 septembre 2020 Statut Membre Dernière intervention 21 janvier 2022 - Modifié le 30 nov. 2020 à 15:41
Bonjour à tous,

J'ai un code qui fonctionne bien pour parser mon JSON, mais j'aimerai extraire un autre champs mais je me retrouve à chaque fois avec des erreurs, ou bien ça ne m'affiche rien.
J'aimerai récupérer maintenant le champs en gras ci dessous, l'id du tag.

Voilà mon JSON:

{
  "STATUS": "OK",
  "todo-items": [
    {
     
      "content": "Reporting Teamwork: récupérer travaux API (30%)",
      "project-name": "Governance and Follow-up SII",
      "todo-list-name": "Teamwork",
      "tags": [
      {
     <gras>  "id" : "1234"</gras>,
       }
       ],
      "subTasks": [
        {
          "content": "HTTP request",
          "project-name": "Governance and Follow-up SII",
          "todo-list-name": "Teamwork",
          "parent-task": {
            "content": "Reporting Teamwork: récupérer travaux API (30%)",
          },
        },
        {
          "content": "Proxy configuration",
          "project-name": "Governance and Follow-up SII",
          "todo-list-name": "Teamwork",
          "parent-task": {
            "content": "Reporting Teamwork: récupérer travaux API (30%)",
          },
        }
      ],
    },
    {
      "content": "Reporting Teamwork: récupérer travaux API (60%)",
      "project-name": "Governance and Follow-up SII",
      "todo-list-name": "Teamwork",
      "subTasks": [
        {
          "content": "Authentication API",
          "project-name": "Governance and Follow-up SII",
          "todo-list-name": "Teamwork",
          "parent-task": {
            "content": "Reporting Teamwork: récupérer travaux API (60%)",
          },
        },
        {
          "content": "Parsing",
          "project-name": "Governance and Follow-up SII",
          "todo-list-name": "Teamwork",
          "parent-task": {
            "content": "Reporting Teamwork: récupérer travaux API (60%)",
          },
        }
      ],
    }
  ]
}



et voici le code en question


import java.util.List;

public class ItemDto {
    public String content;
    public String projectName;
    public String todoListName;
    public List<TaskDto> subTasks;

    public String toString(){
        return "ItemDto [content=" + content + ", projectName=" + projectName + ", todoListName=" + todoListName + ", subTasks=" + subTasks + "]";
    }
}




public class TaskDto {
    public String content;
    public String projectName;
    public String todoListName;

    public String toString(){
        return "TaskDto [content=" + content + ", projectName=" + projectName + ", todoListName=" + todoListName + "]";
    }
}





import java.util.*;
import org.json.*;

public class Parser {

    public static List<ItemDto> readJson(String json) {
        JSONObject rootJson = new JSONObject(json);
        JSONArray itemsJson = (JSONArray) rootJson.get("todo-items");
        List<ItemDto> items = new ArrayList<>(itemsJson.length());
        for (int i = 0; i < itemsJson.length(); i++) {
            items.add(readItem((JSONObject) itemsJson.get(i)));
        }
        return items;
    }

    public static ItemDto readItem(JSONObject itemJson) {
        ItemDto item = new ItemDto();
        item.content = itemJson.getString("content");
        item.projectName = itemJson.getString("project-name");
        item.todoListName = itemJson.getString("todo-list-name");

        JSONArray tasksJson = (JSONArray) itemJson.get("subTasks");
        item.subTasks = new ArrayList<>(tasksJson.length());
        for (int i = 0; i < tasksJson.length(); i++) {
            item.subTasks.add(readTask((JSONObject) tasksJson.get(i)));
        }

        return item;
    }

    public static TaskDto readTask(JSONObject taskJson) {
        TaskDto task = new TaskDto();
        task.content = taskJson.getString("content");
        task.projectName = taskJson.getString("project-name");
        task.todoListName = taskJson.getString("todo-list-name");
        return task;
    }
}



Les classes pour manipuler les données et les présenter comme je le souhaite.


import java.util.List;

public class ProjectBean {
    public HeaderBean header;
    public List<ItemBean> items;

    public String toString(){
        return "ProjectBean [header=" + header + ", items=" + items + "]";
    }
}





import java.util.Objects;

public class HeaderBean {
    public String projectName;
    public String todoListName;

    public String toString(){
        return "HeaderBean [projectName=" + projectName + ", todoListName=" + todoListName + "]";
    }

    public int hashCode(){
        return Objects.hash(projectName, todoListName);
    }

    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        HeaderBean other = (HeaderBean) obj;
        return Objects.equals(projectName, other.projectName) && Objects.equals(todoListName, other.todoListName);
    }
}




import java.util.List;

public class ItemBean {
    public String content;
    public List<String> subTasksContent;

    public String toString(){
        return "ItemBean [content=" + content + ", subTasksContent=" + subTasksContent + "]";
    }
}



Et ensuite le mapping entre les DTO et les Bean :

import java.util.*;

public class ProjectMapper {
    public static List<ProjectBean> projectsFromItems(List<ItemDto> itemDtos) {
        Map<HeaderBean, List<ItemBean>> map = new HashMap<>();
        for (ItemDto itemDto : itemDtos) {
            HeaderBean headerBean = new HeaderBean();
            headerBean.projectName = itemDto.projectName;
            headerBean.todoListName = itemDto.todoListName;

            ItemBean itemBean = new ItemBean();
            itemBean.content = itemDto.content;
            itemBean.subTasksContent = new ArrayList<>();
            for (TaskDto taskDto : itemDto.subTasks) {
                itemBean.subTasksContent.add(taskDto.content);
            }

            List<ItemBean> itemBeans = map.get(headerBean);
            if (itemBeans == null) {
                itemBeans = new ArrayList<>();
                map.put(headerBean, itemBeans);
            }
            itemBeans.add(itemBean);
        }
        List<ProjectBean> projects = new ArrayList<>();
        for (Map.Entry<HeaderBean, List<ItemBean>> entry : map.entrySet()) {
            ProjectBean project = new ProjectBean();
            project.header = entry.getKey();
            project.items = entry.getValue();
            projects.add(project);
        }
        return projects;
    }
}




public static void main(String[] args) throws Exception {
    List<ItemDto> items = Parser.readJson(Files.readString(Paths.get("E:/test.json")));
    List<ProjectBean> projects = ProjectMapper.projectsFromItems(items);
    for (ProjectBean project : projects) {
        System.out.println("Project : " + project.header.projectName);
        System.out.println("List : " + project.header.todoListName);
        for (ItemBean item : project.items) {
            System.out.println("Content : " + item.content);
            for (String subTask : item.subTasksContent) {
                System.out.println("sous tâches : " + subTask);
            }
        }
    }
}