如何将Java对象列表转换为地图列表
我有以下域对象
Class Student {
private int id;
private String name;
private int age;
}
,并且有一个list< student>
如何将其转换为地图列表,如下所示
[{
"id": 1,
"name": "abc",
"age": 2
}, {
"id": 2,
"name": "pqr",
"age": 3
}]
I have the following domain object
Class Student {
private int id;
private String name;
private int age;
}
and I have a List<Student>
How do I convert that into a list of map as follows
[{
"id": 1,
"name": "abc",
"age": 2
}, {
"id": 2,
"name": "pqr",
"age": 3
}]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的方法是在
student
类中创建方法tohashmap()
:我使用
linkedHashmap
来保留插入顺序。完成此操作后,请尝试以下操作:输出:
[{ID = 12123,name = tom,age = 12},{id = 12354,name = george,age = 21},{id = 12245,name = sara = sara = sara ,age = 16},{id = 17642,name = caitlyn,age = 11}]
Easiest way would be to create a method
toHashMap()
in yourStudent
class:I use a
LinkedHashMap
to preserve the insertion order. Once that is done, try this:Output:
[{Id=12123, Name=Tom, Age=12}, {Id=12354, Name=George, Age=21}, {Id=12245, Name=Sara, Age=16}, {Id=17642, Name=Caitlyn, Age=11}]
我会说获取对象并在声明的字段上进行迭代,这足以满足您要做的事情。类似的事情:
尽管如此,似乎您正在尝试将一个普通对象转换为JSON字符串,并且有一些非常好的库。查看此 stackoverflow the of json的转换真的,您要实现的目标。
I'd say getting the object and iterating on the declared fields is good enough for what you're trying to do. Something like this:
Nevertheless, it seems like you're trying to convert an ordinary object to JSON strings and there are libraries that to that super well. Check out this stackoverflow thread about conversion of objects to json if this is really what you're trying to achieve.