简体   繁体   English

如何在json中获取每个对象的级别,其中对象可以具有任意数量的具有相同对象类型的子对象

[英]How to get level of each object in json where objects can have any number of children of same object type

I have an Employee level structure like below image 我有一个像下图这样的员工级结构 在此输入图像描述

This structure is populated and stored with help of json like this 这个结构在这样的json的帮助下填充和存储

 {
  "name": "Lao Lao",
  "title": "general manager",
  "children": [
    {
      "name": "Bo Miao",
      "title": "department manager",
      "children": [
        {
          "name": "Li Jing",
          "title": "senior engineer"
        },
        {
          "name": "Li Xin",
          "title": "senior engineer",
          "children": [
            {
              "name": "To To",
              "title": "engineer"
            },
            {
              "name": "Fei Fei",
              "title": "engineer"
            },
            {
              "name": "Xuan Xuan",
              "title": "engineer"
            }
          ]
        }
      ]
    },
    {
      "name": "Su Miao",
      "title": "department manager",
      "children": [
        {
          "name": "Pang Pang",
          "title": "senior engineer"
        },
        {
          "name": "Hei Hei",
          "title": "senior engineer",
          "children": [
            {
              "name": "Xiang Xiang",
              "title": "UE engineer"
            },
            {
              "name": "Dan Dan",
              "title": "engineer"
            },
            {
              "name": "Zai Zai",
              "title": "engineer"
            }
          ]
        }
      ]
    }
  ]
} 

I want to parse this Json to get all the objects with the level and parent name like this 我想解析这个Json,以获得具有这样的级别和父级名称的所有对象

{name =  Lao lao , parent = null , level = 1 }
{name =  Bao Miao , parent = Lao lao , level = 2 }
..................................................
{name =  Li Jing  , parent = Bao Miao , level = 3 }

How can we parse this with help of java?If there is any library with such functionality, please let me know. 我们如何在java的帮助下解析它?如果有任何具有此类功能的库,请告诉我。

look like I have so much time and waste my time doing this for you because it sound challenging basically I turn this into a jsonObject first then I do a bfs graph walk to find the level and parent told you it is a graph problem again there is some bug on the level but I want the community or you to fix the bug yourself 看起来我有这么多时间,浪费我的时间为你做这个,因为它听起来很有挑战性我先把它变成一个jsonObject然后我做一个bfs图步行找到水平和父母告诉你这是一个图形问题再次有关于这个级别的一些bug,但是我希望社区或你自己修复bug

EDIT : I have fix the level bug for you already again ask me if you have any question 编辑 :我已经修复了你的级别错误你已经再次问我是否有任何问题

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

public class Main {

    public static void main(String[] args) throws Exception{
        String JSON_STRING = "{\n" +
                "  \"name\": \"Lao Lao\",\n" +
                "  \"title\": \"general manager\",\n" +
                "  \"children\": [\n" +
                "    {\n" +
                "      \"name\": \"Bao Miao\",\n" +
                "      \"title\": \"department manager\",\n" +
                "      \"children\": [\n" +
                "        {\n" +
                "          \"name\": \"Li Jing\",\n" +
                "          \"title\": \"senior engineer\"\n" +
                "        },\n" +
                "        {\n" +
                "          \"name\": \"Li Xin\",\n" +
                "          \"title\": \"senior engineer\",\n" +
                "          \"children\": [\n" +
                "            {\n" +
                "              \"name\": \"To To\",\n" +
                "              \"title\": \"engineer\"\n" +
                "            },\n" +
                "            {\n" +
                "              \"name\": \"Fei Fei\",\n" +
                "              \"title\": \"engineer\"\n" +
                "            },\n" +
                "            {\n" +
                "              \"name\": \"Xuan Xuan\",\n" +
                "              \"title\": \"engineer\"\n" +
                "            }\n" +
                "          ]\n" +
                "        }\n" +
                "      ]\n" +
                "    },\n" +
                "    {\n" +
                "      \"name\": \"Su Miao\",\n" +
                "      \"title\": \"department manager\",\n" +
                "      \"children\": [\n" +
                "        {\n" +
                "          \"name\": \"Pang Pang\",\n" +
                "          \"title\": \"senior engineer\"\n" +
                "        },\n" +
                "        {\n" +
                "          \"name\": \"Hei Hei\",\n" +
                "          \"title\": \"senior engineer\",\n" +
                "          \"children\": [\n" +
                "            {\n" +
                "              \"name\": \"Xiang Xiang\",\n" +
                "              \"title\": \"UE engineer\"\n" +
                "            },\n" +
                "            {\n" +
                "              \"name\": \"Dan Dan\",\n" +
                "              \"title\": \"engineer\"\n" +
                "            },\n" +
                "            {\n" +
                "              \"name\": \"Zai Zai\",\n" +
                "              \"title\": \"engineer\"\n" +
                "            }\n" +
                "          ]\n" +
                "        }\n" +
                "      ]\n" +
                "    }\n" +
                "  ]\n" +
                "}] \n";

        JSONObject obj = new JSONObject(JSON_STRING);

        Deque<JSONObject> deque = new ArrayDeque<>();
        Map<String, String> res = new HashMap<>();
        int level = 1;
        res.put("NULL", obj.getString("name")+ "-" + level);
        deque.add(obj);
        Map<String, Integer> levelmap = new HashMap<>();
        levelmap.put(obj.getString("name"), 1);
        while (!deque.isEmpty()){
            JSONObject u = deque.poll();
            try {
                JSONArray children =  u.getJSONArray("children");
                for (int i = 0; i < children.length(); i++) {
                    deque.add(children.getJSONObject(i));
                    levelmap.put(children.getJSONObject(i).getString("name"), levelmap.get(u.getString("name")) + 1);
                    res.put(children.getJSONObject(i).getString("name"), u.getString("name") + "-" + levelmap.get(children.getJSONObject(i).getString("name")));
                }
            }catch (JSONException jex){
                System.out.println("end of the tree");
            }
        }

        //turn it back into a json array format
        String str = new String("[]");

        JSONArray jsonArray = new JSONArray(str);

        System.out.println(res);

        for(String key: res.keySet()){
            String st = new String("{}");
            JSONObject jsonObject = new JSONObject(st);
            //key is parent
            String[] tok = res.get(key).split("-");
            String child = tok[0];
            String mylevel = tok[1];
            jsonObject.put("name", key);
            jsonObject.put("level", mylevel);
            jsonObject.put("parent", child);
            jsonArray.put(jsonObject);
        }

        System.out.println(jsonArray.toString(2));

    }
}

output: 输出:

[
  {
    "parent": "Hei Hei",
    "level": "4",
    "name": "Xiang Xiang"
  },
  {
    "parent": "Lao Lao",
    "level": "2",
    "name": "Bao Miao"
  },
  {
    "parent": "Lao Lao",
    "level": "1",
    "name": "NULL"
  },
  {
    "parent": "Su Miao",
    "level": "3",
    "name": "Hei Hei"
  },
  {
    "parent": "Hei Hei",
    "level": "4",
    "name": "Dan Dan"
  },
  {
    "parent": "Hei Hei",
    "level": "4",
    "name": "Zai Zai"
  },
  {
    "parent": "Li Xin",
    "level": "4",
    "name": "Xuan Xuan"
  },
  {
    "parent": "Su Miao",
    "level": "3",
    "name": "Pang Pang"
  },
  {
    "parent": "Li Xin",
    "level": "4",
    "name": "Fei Fei"
  },
  {
    "parent": "Li Xin",
    "level": "4",
    "name": "To To"
  },
  {
    "parent": "Bao Miao",
    "level": "3",
    "name": "Li Jing"
  },
  {
    "parent": "Lao Lao",
    "level": "2",
    "name": "Su Miao"
  },
  {
    "parent": "Bao Miao",
    "level": "3",
    "name": "Li Xin"
  }
]

Implement Model definition as below. 实现模型定义如下。 Also put level and parentName in Model class. 还将level和parentName放在Model类中。

class Employee{
    String name;
    String title;
    Employee children[];
    int level;
    String parentName;

    @Override
    public String toString(){
        return "{name =  "+name+" , parent = "+parentName+ ", level = "+level+ " }";
    }
}

Parse the json data using GSON API. 使用GSON API解析json数据。

Employee e= new Gson().fromJson(new JsonReader(new FileReader("file.json")), Employee.class);

This is complete program for you. 这是完整的程序。 Finally i was able to write all the code for you after spending an hour on this. 最后,我花了一个小时就能为你编写所有代码。 Working fine so far :) 到目前为止工作正常:)

import java.io.FileReader;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;

public class ParseJson {

    public static void main(String a[]) {
        Gson g = new Gson();
        try {
            Employee e = g.fromJson(new JsonReader(new FileReader("file.json")), Employee.class);

            parseEmployees(e);
            printEmployee(e);
        } catch (Exception e1) {
            e1.printStackTrace();
        }

    }

    private static void parseEmployees(Employee e) {
        setParentAndLevel(e, 1, null);
    }

    private static void setParentAndLevel(Employee e, int lvl, String parent) {
        e.level = lvl;
        e.parentName = parent;
        if (e.children != null && e.children.length > 0) {
            lvl++;
            for (Employee emp : e.children) {
                setParentAndLevel(emp, lvl, e.name);
            }
        }
    }

    public static void printEmployee(Employee e){
        System.out.println(e);
        if (e.children != null && e.children.length > 0) {
            for (Employee emp : e.children) {
                printEmployee(emp);
            }
        }else{
            return ;
            }
        }
    }

    class Employee {
        String name;
        String title;
        Employee children[];
        int level;
        String parentName;

        @Override
        public String toString() {
            return "{name =  " + name + " , parent = " + parentName + ", level = " + level + " }";
        }
    }

Output : 输出:

{name =  Lao Lao , parent = null, level = 1 }
{name =  Bo Miao , parent = Lao Lao, level = 2 }
{name =  Li Jing , parent = Bo Miao, level = 3 }
{name =  Li Xin , parent = Bo Miao, level = 3 }
{name =  To To , parent = Li Xin, level = 4 }
{name =  Fei Fei , parent = Li Xin, level = 4 }
{name =  Xuan Xuan , parent = Li Xin, level = 4 }
{name =  Su Miao , parent = Lao Lao, level = 2 }
{name =  Pang Pang , parent = Su Miao, level = 3 }
{name =  Hei Hei , parent = Su Miao, level = 3 }
{name =  Xiang Xiang , parent = Hei Hei, level = 4 }
{name =  Dan Dan , parent = Hei Hei, level = 4 }
{name =  Zai Zai , parent = Hei Hei, level = 4 }

Yes, you can do this. 是的,你可以这样做。 First, you need to map this json to POJO. 首先,您需要将此json映射到POJO。 So, Create a model class like this 所以,创建一个这样的模型类

class Employee{

String name;
String title;
List<Employee> Children;

}

If you can map this json to POJO. 如果你能将这个json映射到POJO。 Then you only need to run through a loop to get what you want. 然后你只需要通过循环来获得你想要的东西。

暂无
暂无

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

相关问题 如何遍历包含与对象具有相同类型的子对象的对象? - How do I iterate through an object which contain children objects with the same type as the object? Json对象带有2个相同类型的嵌套对象 - Json Object with 2 nested objects of same type 如何将json对象添加到同一级别的另一个json对象中? - How to add json object into another json object at the same level? java如何在没有递归的情况下创建具有相同类型子节点的对象? - How can java create objects with children of the same type without recursion? 同一类型的多个对象如何同时与另一种类型的 object 一起工作? - How can several objects of the same type work with an object of another type at the same time? 如何解析包含多个相同类型的 JSON 对象(不是数组)的 JSON object - How to Parse a JSON object with contains multiple JSON objects ( not an array) of the same type 在对象列表中,只有对象的唯一名称时如何获取对象 - In a list of objects, how can you get the object when you only have the unique name of the object 如何获取对象内的对象名称? (JSON) - How to get names of objects within object? (JSON) 在Java中,如何在单个JSON对象中表示多个(相同类型的)对象 - In Java, How do I represent multiple objects (of same type) in a single JSON object JAVA ::将列表对象1复制到两个对象都具有相同变量的列表对象2 - JAVA :: copy List object1 to list object2 where both the objects have same variables
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM