Jackson Json:如何将数组转换为JsonNode和ObjectNode? [英] Jackson Json: how to convert array to JsonNode and ObjectNode?
问题描述
给定员工和公司类
Company
{
String companyName;
}
Employee
{
String employeeName;
}
我的代码如下
List<Employee> e = new ArrayList<Employee>();
.....
.....
我希望我可以得到这样的结果
i wish i can get result like this
{
"company":{
"companyName":"cName",
"Employee":[
{"employeeName":"myName1"},
{"employeeName":"myName2"},
{"employeeName":"myName3"}
]
}
}
这是一个简单的问题但是我很困惑的事情....
尤其是Gson和Json ....
It is a simple question, however i quite confusing somethings.... Especially Gson And Json....
请不要提议其他图书馆,我 COMPULSORY NEED 这个库可以工作。
由于某些情况,此类 不是 我想要的。
Please do not propose other library, which i COMPULSORY NEED this library to work. And due to some circumstance,this class IS NOT i wanted.
Company
{
String companyName;
List<Employee> employees;
}
因此我需要 手动 把它和序列化为json字符串。
Therefore i need MANUALLY put it,and serialize to json string.
编辑:
@Sotirios Delimanolis类声明是设计
类之间关系的正确方法。但是,这不是我想要的。
EDITED: @Sotirios Delimanolis classes declared is the right way to design the relationship between classes. However, that's not i wanted.
来自@hsluo的答案是正确的!和@Sotirios Delimanolis提到的相同。完全符合这个问题。
The Answer from @hsluo is Correct! and same as what @Sotirios Delimanolis mention. Totally fulfill this question.
我确实找到了另一种使用Hashmap的方法
And i did found another way to do it which using Hashmap
HashMap k = new HashMap();
List<employee> y = new ArrayList<employee>();
y......
k.put("records", y);
k.put("total", total);
然后返回@Responbody,结果与@hsluo回答相同。
and then return to @Responbody, result totally same as @hsluo answered.
感谢@Sotirios Delimanolis,@ hsluo帮助我。
推荐答案
ObjectMapper mapper = new ObjectMapper();
List<Employee> e = new ArrayList<Employee>();
ArrayNode array = mapper.valueToTree(e);
ObjectNode companyNode = mapper.valueToTree(company);
companyNode.putArray("Employee").addAll(array);
JsonNode result = mapper.createObjectNode().set("company", companyNode);
这篇关于Jackson Json:如何将数组转换为JsonNode和ObjectNode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!