gpt4 book ai didi

java - POJO 转换为 JSON 问题

转载 作者:行者123 更新时间:2023-12-02 11:29:16 25 4
gpt4 key购买 nike

我在使用 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;

}

}

最佳答案

解决方案:

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

关于java - POJO 转换为 JSON 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49392189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com