In JavaScript we can do:
function foo() {
...
return {
attr1 : ... ,
attr2 : ...,
};
}
But what is its equivalent in Java?
Because I want to return a custom Json object from my controller after an ajax call and I want to create a new bean.
As Java dictates, you should create a new class and convert it to JSON. Also, you can use Map<String,Object>
to accomplish the same thing. To generate following JSON:
{
"attr1":1,
"attr2":2
}
you can use following code:
Map<String,Object> map = new HashMap<>(3);
map.put("attr1", 1);
map.put("attr2", 2);
and convert it to JSON.
PS: HashMap
in Java causes your heap to increase and unnecessary garbage, so I specified just enough size to keep two elements.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.