欢迎光临
我们一直在努力

将Java对象转换为Map对象

在Java中,你可以使用Jackson库实现Java对象和Map类的转换。

1.获取Jackson

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.3</version>
</dependency>

2.实现转换

1)实体类

package com.inspur.neo4j.domain;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.inspur.neo4j.util.Neo4JCustomIdStrategy;
import org.neo4j.ogm.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图谱节点:动态增加属性
 */
@NodeEntity
public class GraphNode {
    @Id
    @GeneratedValue(strategy = Neo4JCustomIdStrategy.class)
    private String id;

    private String label;

    private String labelName;

    private String typeUri;

    private Double x;

    private Double y;

    private boolean active;

    @Properties
    private Map<String, Object> icon = new HashMap<>();

    @Properties
    private Map<String, Object> properties = new HashMap<>();

    @JsonIgnoreProperties({"startNode", "endNode"})
    @Relationship(type = "EDGE")
    private List<Edge> edges = new ArrayList<>();

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public String getLabelName() {
        return labelName;
    }

    public void setLabelName(String labelName) {
        this.labelName = labelName;
    }

    public String getTypeUri() {
        return typeUri;
    }

    public void setTypeUri(String typeUri) {
        this.typeUri = typeUri;
    }

    public Double getX() {
        return x;
    }

    public void setX(Double x) {
        this.x = x;
    }

    public Double getY() {
        return y;
    }

    public void setY(Double y) {
        this.y = y;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    public Map<String, Object> getIcon() {
        return icon;
    }

    public void setIcon(Map<String, Object> icon) {
        this.icon = icon;
    }

    public Map<String, Object> getProperties() {
        return properties;
    }

    public void setProperties(Map<String, Object> properties) {
        this.properties = properties;
    }

    public List<Edge> getEdges() {
        return edges;
    }

    public void setEdges(List<Edge> edges) {
        this.edges = edges;
    }
}

2)转换过程

ObjectMapper m = new ObjectMapper();
Map<String, Object> node = m.convertValue(graphNode, Map.class);

References

  1. Java – Convert Object to Map example
  2. How to convert a Java object (bean) to key-value pairs (and vice versa)?
赞(0)
未经允许不得转载:Ddmit » 将Java对象转换为Map对象

评论 抢沙发

登录

找回密码

注册