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

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...