Jackson Json:如何将数组转换为 JsonNode 和 ObjectNode? [英] Jackson Json: how to convert array to JsonNode and ObjectNode?

查看:128
本文介绍了Jackson Json:如何将数组转换为 JsonNode 和 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....

请不要推荐其他图书馆,我强制性需要这个图书馆工作.由于某些情况,这门课不是我想要的.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆