将POJO转换为JSON问题

时间:2018-03-20 18:57:46

标签: java json jackson

我遇到使用Jackson将POJO转换为JSON字符串的传统方法的问题。

我得到的输出:

["packagename.RootNode",{"type": "Person","posX":0.0,"posY:0.0}]...

我期望的输出

[{"name":"Brad Pitt",id=13,type="Person","nNode":"{age:54,Married:'Y',...}","posX":0.0,"posY":0.0},...]

基本上,我没有将所有POJO属性作为JSON中的字段,而是获得className和一些属性。

我目前的代码:

private String generateJSONString(List<Node> nodes) throws IOException {
    String JSONGraph="";
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

    // convert Nodes to RootNodes - my custom POJO - definition below
    Iterator<Node> itNode = nodes.iterator();
    List<RootNode> rtNodeList = new ArrayList<>();
    while(itNode.hasNext()) {
        Node node = itNode.next();
        RootNode rtNode = new RootNode(node);
        rtNodeList.add(rtNode);
    }

    for (RootNode vertex: rtNodeList) {

        //print JSON version of vertex
        JSONGraph += objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(vertex);
    }
    return JSONGraph;
}

自定义POJO,RootNode:

package com.aaman.neo4j;


public class RootNode implements NodeInfo{
 protected String name;
 protected String id;
 protected String type;
 protected Map<String,Object> nNode;
 protected double posX,posY;

 protected RootNode() {
    name="";
    id="";
    type="";
    nNode=null;
    posX=0.0;
    posY=0.0;
 }
 protected RootNode(Node n) {
    super();

    this.name = n.getProperty("name").toString();
    n.getProperty("type").toString();
    this.id = ((Long)n.getId()).toString();
    this.nNode = n.getAllProperties(); // creates a map of all props
    this.posX=0.0;
    this.posY=0.0;
}

//Simple toString function as I use this in a String labeller
// if Jackson writeValueAsString expects a detailed JSON-to-String mapping in the toString function, 
// how does one have two versions of the toString function?
@Override
public String toString() {
    return name;

}

}

1 个答案:

答案 0 :(得分:1)

<强>解决方案:

POJO类中的属性需要正确命名的setter和getter。 getName,setName,getId,setId的任何变体(假设属性为name,id)都会导致objectMapper.WriteValueAsString跳过属性