【问题标题】:Swift 2.0 - Rearranging a JSON object by sub arraySwift 2.0 - 按子数组重新排列 JSON 对象
【发布时间】:2016-02-22 07:59:53
【问题描述】:

我正在使用 SwiftyJSON 在 JSON 中创建数据字典。 现在我想通过friend_health_points 安排一个名为fb_friends 的子词典。

我尝试使用排序或任何其他操作,但出现字符串/JSON 错误。

所以基本上我正在尝试对其进行排序,以便在该数据字典中将 150 个健康点排在第一位,将 20 个排在最后。

这是数据:

var data: JSON = [
        "user_id": 7742,
        "name": "Bla",
        "fb_friends": [
            [
                "friend_id": 202072,
                "friend_name": "Bla Bla",
                "friend_photo_url": "https://www.gravatar.com/avatar/",
                "friend_health_points": 50,
            ],
            [
                "friend_id": 502333,
                "friend_name": "hdfghdfghfdgh",
                "friend_photo_url": "https://www.gravatar.com/avatar/",
                "friend_health_points": 150,
            ],
            [
                "friend_id": 202072,
                "friend_name": "gjhkghjk",
                "friend_photo_url": "https://www.gravatar.com/avatar/",
                "friend_health_points": 20,
            ]
]

【问题讨论】:

  • 你的json无效
  • json 工作正常...

标签: arrays json sorting swift2 swifty-json


【解决方案1】:

这是一个没有第三方库的解决方案

var data = [
  "user_id": 7742,
  "name": "Bla",
  "fb_friends": [
    [
      "friend_id": 202072,
      "friend_name": "Bla Bla",
      "friend_photo_url": "https://www.gravatar.com/avatar/",
      "friend_health_points": 50,
    ],
    [
      "friend_id": 502333,
      "friend_name": "hdfghdfghfdgh",
      "friend_photo_url": "https://www.gravatar.com/avatar/",
      "friend_health_points": 150,
    ],
    [
      "friend_id": 202072,
      "friend_name": "gjhkghjk",
      "friend_photo_url": "https://www.gravatar.com/avatar/",
      "friend_health_points": 20,
    ]
  ]
]

let friends = (data["fb_friends"] as! [[String:AnyObject]]).sort{ ($0["friend_health_points"] as! Int) > $1["friend_health_points"] as! Int}
data["fb_friends"] = friends
print(data)

let json = JSON(data)

【讨论】:

  • 谢谢 vadian,但我需要它作为 JSON 类型,我正在构建应用程序以使用 3rd 方 API。
  • 您可以使用let json = JSON(data)从排列好的字典中轻松创建JSON对象
【解决方案2】:

好的,我找到了答案,因为对象是SwiftyJSON 类型,我可以使用arrayValue 将其提取到数组中。 所以这会给我一个排序好的朋友数组。

let fbFriends = data["fb_friends"]
let friendsArray = fbFriends.arrayValue
let sortedFriends = friendsArray.sort { $0["friend_health_points"].doubleValue > $1["friend_health_points"].doubleValue }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 2022-01-23
    相关资源
    最近更新 更多