将数组列表转换为Json Array Kotlin

问题描述 投票:0回答:1

我正在尝试通过gson进行转换,但没有得到我想要的准确的json数组

我正在尝试这样做

 for (x in 0 until selectedMedia.size) {
                    Log.e("tsttttAfter", selectedMedia.get(x).toString() + "________" + x.toString())

                    if (selectedMedia[x]) {

                        var data = Media(mediaArray[x]._id, mediaArray[x].title, mediaArray[x].url, mediaArray[x].thumbnailURL)

                        mediaArray1.add(data)

                    }

                }
                Log.e("mediaArray1Size", mediaArray1.toString())

                val jsonElements: JsonArray = Gson().toJsonTree(mediaArray1) as JsonArray
                jsonElements.add("media")
                Log.e("jsonElement", jsonElements.toString())

[Media(_id=5e724ddf1e22ea0017ec0b40, title=, url=https://y4planet.s3-us-west-2.amazonaws.com/projectvideos/a5cb8f13-8da7-44e0-b76e-9a21226173355e57603bd4c277001754b921_SampleVideo_1280x720_2mb.mp4, thumbnailURL=https://y4planet.s3-us-west-2.amazonaws.com/thumbnail/82ff0321-6936-11ea-a1be-029fabf0d41e.jpg, isSelected=false), Media(_id=5e724e391e22ea0017ec0b42, title=, url=https://y4planet.s3-us-west-2.amazonaws.com/projectvideos/4850a6c4-75bc-475d-89b4-66d96d32bfb95e57603bd4c277001754b921_Mountains31175.mp4, thumbnailURL=https://y4planet.s3-us-west-2.amazonaws.com/thumbnail/b861afba-6936-11ea-a1be-029fabf0d41e.jpg, isSelected=false), Media(_id=5e73b2edbcec690017d9349b, title=, url=https://y4planet.s3-us-west-2.amazonaws.com/projectvideos/6423ef82-b57d-4113-95d4-fbb19c3de63c5e57603bd4c277001754b921_Hang30902.mp4, thumbnailURL=https://y4planet.s3-us-west-2.amazonaws.com/thumbnail/54c93902-6a0b-11ea-a1be-029fabf0d41e.jpg, isSelected=false)]

want to convert this arraylist into like this

[{"media": {"_id":"5e73b2edbcec690017d9349b","thumbnailURL":"https://y4planet.s3-us-west-2.amazonaws.com/thumbnail/54c93902-6a0b-11ea-a1be-029fabf0d41e.jpg","title":"","url":"https://y4planet.s3-us-west-2.amazonaws.com/projectvideos/6423ef82-b57d-4113-95d4-fbb19c3de63c5e57603bd4c277001754b921_Hang30902.mp4"}},{"media": {"_id":"5e73b309bcec690017d9349c","thumbnailURL":"https://y4planet.s3-us-west-2.amazonaws.com/thumbnail/65b004fe-6a0b-11ea-a1be-029fabf0d41e.jpg","title":"","url":"https://y4planet.s3-us-west-2.amazonaws.com/projectvideos/d962f40c-8811-491c-8c32-7601faa86f475e57603bd4c277001754b921_Night28860.mp4"}}]
android android-studio kotlin arraylist gson
1个回答
0
投票

您必须创建一个数据类来像这样包装您的媒体对象

data class MediaWrapper(val media: Media)

该包装将使您的JSON输出在每个对象条目之前具有"media"属性。

您的媒体对象将保持不变。唯一的区别是,现在您的ArrayList将不再是Media的列表,而是MediaWrapper的列表(或您要调用的任何名称)。

然后,要获得您要查找的JSON输出,只需执行以下操作:

Gson().toJson(array)

© www.soinside.com 2019 - 2024. All rights reserved.