如何在java中解析复杂的嵌套jsonarray树

如何在java中解析复杂的嵌套jsonarray树,java,arrays,json,Java,Arrays,Json,我有一个JSON数组,如下所示: [{ "name": "com", "children": [ { "name": "project", "children": [ { "name": "server" }, { "name": "client", "children": [ { "name":

我有一个JSON数组,如下所示:

[{
  "name": "com",
  "children": [
    {
      "name": "project",
      "children": [
        {
          "name": "server"
        },
        {
          "name": "client",
          "children": [
            {
              "name": "util"
            }
          ]
        }
      ]
    }
  ]
}]
我需要所有JSON对象的所有名称。有什么方法可以在java中实现这一点吗

我想要一个递归函数

我的预期结果如下:

[
    {name:"com"},
    {"name":"project"},
    {"name":"server"},
    {"name":"client"},
    {"name":"util"}]
只需尝试触发“[”和“]”。递归地传递一个字符串,该字符串可以将json中被剪切的utile部分添加到新格式中。最后,您可以将此字符串返回到原始调用。。当递归结束时

我为你写了一个例子,但是用C#写的,没有递归似乎更容易

   public string GetNames(string originalJson)
        {
            string namesString = "[";
            bool newItem = false;

            for(int i = 0; i < originalJson.Length; i++ )
            {                
                if(newItem)
                {
                    if (originalJson[i] == ',')
                    {
                        newItem = false;
                        namesString += "}";
                    }

                    else
                        namesString += originalJson[i];

                }
                else if (originalJson[i] == '{')
                {
                    newItem = true;
                    namesString += "{";
                }


            }
            namesString = namesString.Substring(0, namesString.Length - 1);
            namesString += "]";
            return namesString;
        }
publicstringgetnames(stringoriginaljson)
{
字符串名称字符串=“[”;
bool newItem=false;
for(int i=0;i

我不确定这是否是您要查找的内容。

这是一个简单的递归函数,用于从json数组中获取所有
名称
属性:

public静态集合getAllName(JSONArray JSONArray,列表名称){
for(int i=0;i
这将为您提供一个可用于构建新json数组的名称列表。 一种可能的方法是:

publicstaticjsonarray getJsonArraysOfNames(列表名){
JSONArray JSONArray=新的JSONArray();
for(字符串名称:名称){
JSONObject对象=新的JSONObject();
object.put(“name”,name);
jsonArray.put(对象);
}
返回jsonArray;
}
更新 如果您喜欢一体式解决方案,则可以采用以下方法:

publicstaticjsonarray getNames(JSONArray输入阵列、JSONArray输出阵列){
for(int i=0;i
编写了一个小程序来解决您的问题

一个递归类型实体,它有两个属性,类型为字符串的“name”类型为列表的“children”。因为这是和平JSON的结构。因此,可以使用Jackson API在一行中轻松解析JSON

List<Entity> clas = mapper.readValue(json,
                mapper.getTypeFactory().constructCollectionType(List.class, Entity.class));
List clas=mapper.readValue(json,
getTypeFactory().ConstructionCollectionType(List.class,Entity.class));
成功创建对象后,我们所需要做的就是在层次结构中递归遍历它,并在每个步骤中返回name属性和一些额外的文本,从而为结果提供一个有效的JSON表单

Main.java

import java.io.IOException;
import java.util.List;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class Main {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {

    String json = "[{\"name\":\"com\",\"children\":[{\"name\":\"project\",\"children\":[{\"name\":\"server\"},{\"name\":\"client\",\"children\":[{\"name\":\"util\"}]}]}]}]";

    ObjectMapper mapper = new ObjectMapper();
    List<Entity> clas = mapper.readValue(json,
            mapper.getTypeFactory().constructCollectionType(List.class, Entity.class));

    String names = getChildren(clas);
    String result = "[" + names.substring(0, names.length() - 1) + "]";

    System.out.println(result);
}

private static String getChildren(List<Entity> clas) {
    String names = "";
    for (Entity class1 : clas) {
        if (class1.getChildren() == null) {
            names += "{name : \"" + class1.getName() + "\"},";
            if (clas.indexOf(class1) == (clas.size() - 1)) {
                return names;
            }
            continue;
        }
        names += "{name : \"" + class1.getName() + "\"},";

        names += getChildren(class1.getChildren());
    }
    return names;
}
}
import java.util.List;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public  class Entity {

    String name;
    List<Entity> children;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Entity> getChildren() {
        return children;
    }

    public void setChildren(List<Entity> children) {
        this.children = children;
    }}
import java.io.IOException;
导入java.util.List;
导入org.codehaus.jackson.JsonParseException;
导入org.codehaus.jackson.map.JsonMappingException;
导入org.codehaus.jackson.map.ObjectMapper;
公共班机{
公共静态void main(字符串[]args)抛出JsonParseException、JsonMappingException、IOException{
字符串json=“[{\'name\':\'com\',\'children\':[{\'name\':\'project\',\'children\':[{\'name\':\'server\'},{\'name\':\'client\',\'children\':[{\'name\':\'util\'}]}];
ObjectMapper mapper=新的ObjectMapper();
List clas=mapper.readValue(json,
getTypeFactory().ConstructionCollectionType(List.class,Entity.class));
字符串名称=getChildren(clas);
字符串结果=“[”+名称.子字符串(0,名称.长度()-1)+“]”;
系统输出打印项次(结果);
}
私有静态字符串getChildren(列表类){
字符串名称=”;
对于(实体类别1:clas){
if(class1.getChildren()==null){
名称+=“{name:\”“+class1.getName()+“\”},”;
if(类别索引of(class1)=(类别大小()-1)){
返回姓名;
}
继续;
}
名称+=“{name:\”“+class1.getName()+“\”},”;
names+=getChildren(class1.getChildren());
}
返回姓名;
}
}
Entity.java

import java.io.IOException;
import java.util.List;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class Main {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {

    String json = "[{\"name\":\"com\",\"children\":[{\"name\":\"project\",\"children\":[{\"name\":\"server\"},{\"name\":\"client\",\"children\":[{\"name\":\"util\"}]}]}]}]";

    ObjectMapper mapper = new ObjectMapper();
    List<Entity> clas = mapper.readValue(json,
            mapper.getTypeFactory().constructCollectionType(List.class, Entity.class));

    String names = getChildren(clas);
    String result = "[" + names.substring(0, names.length() - 1) + "]";

    System.out.println(result);
}

private static String getChildren(List<Entity> clas) {
    String names = "";
    for (Entity class1 : clas) {
        if (class1.getChildren() == null) {
            names += "{name : \"" + class1.getName() + "\"},";
            if (clas.indexOf(class1) == (clas.size() - 1)) {
                return names;
            }
            continue;
        }
        names += "{name : \"" + class1.getName() + "\"},";

        names += getChildren(class1.getChildren());
    }
    return names;
}
}
import java.util.List;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public  class Entity {

    String name;
    List<Entity> children;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Entity> getChildren() {
        return children;
    }

    public void setChildren(List<Entity> children) {
        this.children = children;
    }}
import java.util.List;
导入org.codehaus.jackson.annotate.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown=true)
公共类实体{
字符串名;
列出儿童名单;
公共字符串getName(){
返回名称;
}
公共void集合名(字符串名){
this.name=名称;
}
公共列表getChildren(){
返回儿童;
}
公共子项(列出子项){
这个。孩子=孩子;
}}

到目前为止您尝试了什么?为什么不起作用?JSONArray ja=new JSONArray(myarray);JSONObject jo=ja.getJSONObject(0);System.out.println(jo.getString(“name”);实际上我正在尝试这样做,所以它的解决方法我需要一个读取数组中嵌套数组的函数,并且我的数据是d