Java 如何使用Jackson将自迭代ArrlyList转换为json

Java 如何使用Jackson将自迭代ArrlyList转换为json,java,json,jackson,Java,Json,Jackson,我想将列表数据转换为下面的json结构。为此,我将mysql中的数据提取到arraylist中,并编写了pojo类EducationDTO { "id": "1", "name": "EDUCATION", "data": "", "children": [ { "id": "1.1", "name": "STREAM-ENGG", "data": "", "children": [ {

我想将列表数据转换为下面的json结构。为此,我将mysql中的数据提取到arraylist中,并编写了pojo类EducationDTO

{
"id": "1",
"name": "EDUCATION",
"data": "",
"children": [
    {
        "id": "1.1",
        "name": "STREAM-ENGG",
        "data": "",
        "children": [
            {
                "id": "1.11",
                "name": "COMPUTER SCIENCE",
                "data": "",
                "children": [
                    {
                        "id": "1.111",
                        "name": "YEAR-01",
                        "data": ""
                    },
                    {
                        "id": "1.112",
                        "name": "YEAR-02",
                        "data": ""
                    },
                    {
                        "id": "1.113",
                        "name": "YEAR-03",
                        "data": ""
                    },
                    {
                        "id": "1.114",
                        "name": "YEAR-04",
                        "data": ""
                    }
                ]
            },
            {
                "id": "1.12",
                "name": "EXTC",
                "data": "",
                "children": [
                    {
                        "id": "1.121",
                        "name": "YEAR-01",
                        "data": ""
                    },
                    {
                        "id": "1.122",
                        "name": "YEAR-02",
                        "data": ""
                    },
                    {
                        "id": "1.123",
                        "name": "YEAR-03",
                        "data": ""
                    },
                    {
                        "id": "1.124",
                        "name": "YEAR-04",
                        "data": ""
                    }
                ]
            },
            {
                "id": "1.13",
                "name": "BIOMEDICAL",
                "data": "",
                "children": [
                    {
                        "id": "1.131",
                        "name": "YEAR-01",
                        "data": ""
                    },
                    {
                        "id": "1.132",
                        "name": "YEAR-02",
                        "data": ""
                    },
                    {
                        "id": "1.133",
                        "name": "YEAR-03",
                        "data": ""
                    },
                    {
                        "id": "1.134",
                        "name": "YEAR-04",
                        "data": ""
                    }
                ]
            },
            {
                "id": "1.14",
                "name": "CHEMICAL",
                "data": "",
                "children": [
                    {
                        "id": "1.141",
                        "name": "YEAR-01",
                        "data": ""
                    },
                    {
                        "id": "1.142",
                        "name": "YEAR-02",
                        "data": ""
                    },
                    {
                        "id": "1.143",
                        "name": "YEAR-03",
                        "data": ""
                    },
                    {
                        "id": "1.144",
                        "name": "YEAR-04",
                        "data": ""
                    }
                ]
            }
        ]
    },
    {
        "id": "1.2",
        "name": "STREAM-MEDICAL",
        "data": "",
        "children": [
            {
                "id": "1.21",
                "name": "MBBS",
                "data": "",
                "children": [
                    {
                        "id": "1.211",
                        "name": "YEAR-01",
                        "data": ""
                    },
                    {
                        "id": "1.212",
                        "name": "YEAR-02",
                        "data": ""
                    },
                    {
                        "id": "1.212",
                        "name": "YEAR-03",
                        "data": ""
                    },
                    {
                        "id": "1.213",
                        "name": "YEAR-04",
                        "data": ""
                    },
                    {
                        "id": "1.214",
                        "name": "YEAR-05",
                        "data": ""
                    }
                ]
            },
            {
                "id": "1.22",
                "name": "BHMS",
                "data": "",
                "children": [
                    {
                        "id": "1.221",
                        "name": "YEAR-01",
                        "data": ""
                    },
                    {
                        "id": "1.222",
                        "name": "YEAR-02",
                        "data": ""
                    },
                    {
                        "id": "1.223",
                        "name": "YEAR-03",
                        "data": ""
                    }
                ]
            },
            {
                "id": "1.31",
                "name": "BDS",
                "data": "",
                "children": [
                    {
                        "id": "1.311",
                        "name": "YEAR-01",
                        "data": ""
                    },
                    {
                        "id": "1.312",
                        "name": "YEAR-02",
                        "data": ""
                    },
                    {
                        "id": "1.313",
                        "name": "YEAR-03",
                        "data": ""
                    },
                    {
                        "id": "1.314",
                        "name": "YEAR-04",
                        "data": ""
                    }
                ]
            }
        ]
    }
]
}

我很麻烦我写的逻辑会包含重复的代码

JsonFactory jFactory=new JsonFactory();
Writer writer = new StringWriter();
JsonGenerator jsGenerator = jFactory.createJsonGenerator(writer);
jsGenerator.writeStartObject();

jsGenerator.writeEndObject();
for(EducationDTO eDto:vDto.getEducationDTOList()){
    if(eDto.getParent_Id().equalsIgnoreCase("0")){
        jsGenerator.writeStringField("id",eDto.getUnid());
        jsGenerator.writeStringField("name",eDto.getNode_Name());
        jsGenerator.writeStringField("data","");
        if(eDto.getHasChildren().equalsIgnoreCase("YES")){
            jsGenerator.writeFieldName("children");
            jsGenerator.writeStartArray();
            for(EducationDTO eDto2:vDto.getEducationDTOList()){
                if(eDto2.getParent_Id().equalsIgnoreCase(eDto.getUnid())){
                    jsGenerator.writeStartObject();
                    jsGenerator.writeStringField("id",eDto.getUnid());
                    jsGenerator.writeStringField("name",eDto2.getNode_Name());
                    jsGenerator.writeStringField("data","");
                    if(eDto2.getHasChildren().equalsIgnoreCase("YES")){
                        jsGenerator.writeFieldName("children");
                        jsGenerator.writeStartArray();
                        for(EducationDTO eDto3:vDto.getEducationDTOList()){
                            if(eDto3.getParent_Id().equalsIgnoreCase(eDto2.getUnid())){
                                jsGenerator.writeStartObject();
                                jsGenerator.writeStringField("id",eDto.getUnid());
                                jsGenerator.writeStringField("name",eDto3.getNode_Name());
                                jsGenerator.writeStringField("data","");
                                if(eDto2.getHasChildren().equalsIgnoreCase("YES")){
                                    jsGenerator.writeFieldName("children");
                                    jsGenerator.writeStartArray();
                                    for(EducationDTO eDto4:vDto.getEducationDTOList()){
                                        if(eDto4.getParent_Id().equalsIgnoreCase(eDto3.getUnid())){
                                            jsGenerator.writeStartObject();
                                            jsGenerator.writeStringField("id",eDto4.getUnid());
                                            jsGenerator.writeStringField("name",eDto4.getNode_Name());
                                            jsGenerator.writeStringField("data","");
                                            jsGenerator.writeEndObject();
                                        }
                                    }
                                    jsGenerator.writeEndArray();

                                }
                                jsGenerator.writeEndObject();
                            }
                        }
                        jsGenerator.writeEndArray();

                    }
                    jsGenerator.writeEndObject();
                }
            }
            jsGenerator.writeEndArray();

        }
        break;
    }
}


jsGenerator.close();

下面是将Java对象转换为json的方法

ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\EducationDTO.json"), EducationDTO);
ArrayList也是一个Java对象,即使Java对象有迭代对象,它也会将其转换为JSON

假设有递归对象,比如

类A{A;//setter和getter}

在模型类中使用以打断循环

或者跟

使用下面的注释并注释每个类。
@JsonIdentityInfo(generator=JSOGGenerator.class)

请使用如下代码:

import java.lang.reflect.Field;
import java.util.List;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonConvertor {

private static GsonBuilder gsonBuilder;
private static Gson gson;

private JsonConvertor() {

}
public static Object fromJson(String json, Class clz)
{
    gson=new Gson();
    return gson.fromJson(json,clz);
}

public static String toJson(Object obj) {
    gsonBuilder = new GsonBuilder();
    gsonBuilder = gsonBuilder
            .addSerializationExclusionStrategy(new CustomIclusionStrategy(
                    obj.getClass()));
    gson = gsonBuilder.create();
    String json = gson.toJson(obj);
    return json;
}
}


那么,你走对了道路;)我在这个问题上回答了相同的想法是的,但我在列表中的数据是指列表中的其他元素,如列表第二项可能是第一项的子项,第三项可能是第二项的子项我无法正确迭代我的arraylist,我可以向您显示我的代码吗?如果我在arraylist中添加了更多数据,此逻辑失败,请检查..@SafwanHijazi-是否可以根据您的答案创建我的json字符串?因为我的json数据添加了parent->children(parent)->children(parent)->childrenthanks很多,但是根据我的要求,我必须对json字符串做一些更改,json字符串将返回相同的结果,并且如果它仍然增加,我将得到与每个json字符串相同的结果。请检查更新的json字符串。我添加了更多元素和动态id。它是动态的,只需使用您想要的值填充对象并调用json方法
class CustomIclusionStrategy implements ExclusionStrategy {

private Class classToIclude;

private Field[] declaredFields;


private List<FieldAttributes> fields;

public CustomIclusionStrategy(List<FieldAttributes> fields) {
    this.fields = fields;
}

public CustomIclusionStrategy(Class classToIclude) {
    this.classToIclude = classToIclude;
    this.declaredFields=classToIclude.getDeclaredFields();

}

// called only if shouldSkipClass returns false
@Override
public boolean shouldSkipField(FieldAttributes f) {

    try {
        classToIclude.getSuperclass().getDeclaredField(f.getName());
        System.out.println(f.getName());
        return true;
    } catch (Exception e) {
    } 
    return false;

}

@Override
public boolean shouldSkipClass(Class<?> clazz) {
    // if returns false shouldSkipField will be called, otherwise 
 //shouldSkipField will not be called
    return false;
}
}
 import java.util.ArrayList;
 import java.util.List;


public class Node {

String id;
String name;
String data;
List<Node> children;
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getData() {
    return data;
}
public void setData(String data) {
    this.data = data;
}
public List<Node> getChildren() {
    return children;
}
public void setChildren(List<Node> children) {
    this.children = children;
}

public String toJson()
{
    return JsonConvertor.toJson(this);
}

public Node(String id, String name, String data) {
    super();
    this.id = id;
    this.name = name;
    this.data = data;
}
public Node(String id, String name, String data, List<Node> children) {
    super();
    this.id = id;
    this.name = name;
    this.data = data;
    this.children = children;
}
 public static void main(String[] args) {

    Node n5=new Node("1","YEAR-01","");
    List<Node> list3=new ArrayList<Node>();
    list3.add(n5);


    Node n3=new Node("1","COMPUTER SCIENCE","",list3);
    Node n4=new Node("1","EXTC","",list3);
    List<Node> list=new ArrayList<Node>();
    List<Node> list2=new ArrayList<Node>();

    list2.add(n3);

    list2.add(n4);
    Node n2=new Node("1","STREAM-ENGG","",list2);

    list.add(n2);


    Node n1=new Node("1","EDUCATION","",list);
    System.out.println(n1.toJson());

}

}
{
    "id": "1",
    "name": "EDUCATION",
    "data": "",
    "children": [{
        "id": "1",
        "name": "STREAM-ENGG",
        "data": "",
        "children": [{
            "id": "1",
            "name": "COMPUTER SCIENCE",
            "data": "",
            "children": [{
                "id": "1",
                "name": "YEAR-01",
                "data": ""
            }]
        },
        {
            "id": "1",
            "name": "EXTC",
            "data": "",
            "children": [{
                "id": "1",
                "name": "YEAR-01",
                "data": ""
            }]
        }]
    }]
}