anarche
anarche

Reputation: 536

Convert POJO to JSON problems

I'm having issues with the traditional way to convert POJOs to a JSON string using Jackson.

The output I get:

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

The output I expect

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

Basically, I'm not getting all the POJO attributes as fields in the JSON, but instead the className and a few properties.

My current code:

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;
}

The Custom 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;

}

}

Upvotes: 0

Views: 113

Answers (1)

anarche
anarche

Reputation: 536

Solution:

The attributes in the POJO class required properly named setters and getters. Any variation from the getName,setName, getId, setId (assuming the attributes are name,id) cause the objectMapper.WriteValueAsString to skip the attributes

Upvotes: 1

Related Questions