GSON - 从 Java 创建 JSON 树结构

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11194343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:10:46  来源:igfitidea点击:

GSON - Creating JSON tree structure from Java

javajsongson

提问by user82302124

Have a couple questions, using GSON. I have a feeling that GSON might not be what I am looking for in terms of a library that will be able to give me a JSON object that I can use later.

有几个问题,使用 GSON。我有一种感觉,GSON 可能不是我正在寻找的库,它能够为我提供一个我以后可以使用的 JSON 对象。

I am reading data from a database to populate a json object that I will later use. The output of the json object should look similar to the json below, which involves parents and children. It forms a small tree based structure:

我正在从数据库中读取数据以填充稍后将使用的 json 对象。json 对象的输出应该与下面的 json 类似,其中涉及父级和子级。它形成了一个基于小树的结构:

var json = { 
         id: "1", 
         name: "Joe Smith", 
         data: { 
         "email": "",
         "phone": "123-123-1233"},
         children: [{
                        id: "Tim Anderson",
                        name: "Tim Anderson",
                        data: { 
                             "email": "[email protected]",
                             "phone": "123-123-1233"
                        },
                        children: []
                    },{
                        id: "Christopher Johnson",
                        name: "Christopher Johnson",
                        data: {  
                             "email": "[email protected]",
                             "phone": "123-123-1233"
                        },
                        children: []
                    },{
                        id: "Kate Green",
                        name: "Kate Green",
                        data: {

                        },
                        children: [{
                            id: "Gary Jones",
                            name: "Gary Jones",
                            data: {},
                            children: []
                        }, {
                            id: "Melissa Brand",
                            name: "Melissa Brand",
                            data: {},
                            children: []
                        }]
                    }
                    ] 
    }

How do I create a GSON object, similar to the structure above, that I can serialize to JSON that has this type of hierarchy? I've tried using maps and other collections - but I am having difficulty getting the results I want. Hence why I ask if GSON is what I really want for a JSON serialization.

我如何创建一个 GSON 对象,类似于上面的结构,我可以序列化为具有这种层次结构的 JSON?我试过使用地图和其他集合 - 但我很难得到我想要的结果。因此,为什么我问 GSON 是否是我真正想要的 JSON 序列化。

采纳答案by Nishant

Let me give you a hint

让我给你一个提示

make a Person and a Data class (POJO) like this

像这样制作一个人和一个数据类(POJO)

Person
  String id
  String name
  Data data
  List<Person> children

Data
  String email
  String phone

回答by jmishra

Have you tried the default java JSONTokenerand other similar parsers?

您是否尝试过默认的 javaJSONTokener和其他类似的解析器?

      BufferedReader reader = new BufferedReader(new FileReader("jsonfile.json"));
     StringBuilder builder=new StringBuilder();
     for(String line=null;(line = reader.readLine()) != null;){
     builder.append(line).append("\n");
     }
    JSONTokener jsonTokener=new JSONTokener(builder.toString());
    JSONObject finalJson=new JSONObject(jsonTokener);

In your case if you want to find additional data in a hierarchy inside, then iterate over as follows

在您的情况下,如果您想在内部层次结构中查找其他数据,请按如下方式进行迭代

 JSONArray children=finalJson.getJSONArray("children");
 for(int i = 0;i<children.length;i++){
 JSONObject childRecData = children.getJSONObject(i); //returns the ith JSONObject containing id, name, data, etc.
 int id = childRecData.getString();
 String name = childRecData.getString();
 JSONObject data = childRecData.getJSONObject(0);
 }

NOTEThat for larger JSON files (files which have ridiculous levels of hierarchy) such as an HTTP database requests GSON's POJO (Plain Old Java Objects) model as suggested by Nishant is recommended

注意对于较大的 JSON 文件(具有荒谬层次的文件),例如 HTTP 数据库请求 Nishant 建议的 GSON 的 POJO(Plain Old Java Objects)模型

Here's more information

这里有更多信息

Here was a similar question

这是一个类似的问题