Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

java - Jackson Json: how to convert array to JsonNode and ObjectNode?

Given Employee and company class

Company
{
    String companyName;
}

Employee
{
    String employeeName;
}

and my code like the following

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

Therefore i need MANUALLY put it,and serialize to json string.

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.

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

and then return to @Responbody, result totally same as @hsluo answered.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...