Given Employee and company class

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"}
                ]
              }
}

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

因此,我需要将其放入MANUALLY,并序列化为json字符串.

EDITED: @Sotirios Delimanolis classes declared is the right way to design the relationship between classes. However, that's not i wanted.

The Answer from @hsluo is Correct! and same as what @Sotirios Delimanolis mention. Totally fulfill this question.

我确实找到了另一种方法,那就是使用Hashmap

HashMap k = new HashMap();
List<employee> y = new ArrayList<employee>();
y......
k.put("records", y);
k.put("total", total);

然后返回@Responbody,结果与@hsluo完全相同.

AND thanks @Sotirios Delimanolis, @hsluo to help me.

推荐答案

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

Json相关问答推荐

替换字符串中特殊字符的Jolt变换

如何编写MongoDB查询以返回数组数组

如何使用JQ打印每个根级对象键一行?

过go 24小时内判断员事件的EventBridge事件模式

使用JQ将对象数组转换为平面数组

419(未知状态)使用laravel处理PUT请求

如何避免解析 ISuperObject 类型字段中的 json 对象

Jolt 规范将父对象中的所有键应用于数组中的所有对象

我无法在 Go - Gin 中解析日期/时间

如何将从嵌套 Select 返回的空值转换为空数组?

使用 jq Select 键:值并输出为数组

如何限制resolveJsonModule的范围?

如何对使用转换器的 Grails 服务进行单元测试?

Angularjs访问本地json文件

JSON RPC - 什么是id?

什么是类型和类型令牌?

jquery用json数据填充下拉列表

Laravel 5 控制器将 JSON 整数作为字符串发送

使用 JSON.NET 序列化/反序列化对象字典

在没有 ASP.NET Core 的情况下将 IConfigurationSection 绑定到复杂对象