-5

How to fetch values from JSON response in swift? Here i want to loop the order object values inorder to get the dictionary values based on their key. Can anyone suggest me a solution please.

{
    "order": [
        "abc",
        "def",
        "ghi",
    ],
    "posts": {
         "abc": {
             "id": "abc",
             "user_id": "q",
             "channel_id": "qwer",
             "message": "dsd"
         },
        "def": {
            "id": "def",
            "user_id": "w",
            "channel_id": "werg",
            "message": "Gg"
        },
        "ghi": {
            "id": "ghi",
            "user_id": "v",
            "channel_id": "bnm",
            "message": "Ss"
        }
    }
}
iWheelBuy
  • 5,470
  • 2
  • 37
  • 71
gunjan
  • 21
  • 1
  • 6
  • 2
    You need `JSONSerialization` or `JSONDecoder`. Please search: [There are more than 3000 related questions here on SO](https://stackoverflow.com/search?q=%5BSwift%5D+parse+json). In my answer of the question [Correctly Parsing JSON in Swift 3](https://stackoverflow.com/questions/39423367/correctly-parsing-json-in-swift-3/39423764#39423764) there is a quick tutorial how to read JSON. It's pretty simple. – vadian Mar 02 '18 at 09:28
  • have you tried anything? google some tutorial, here is some good/lazy tool: https://github.com/SwiftyJSON/SwiftyJSON – zheck Mar 02 '18 at 09:33

1 Answers1

0

Here's what you can do, Change your JSON string into Data using String.Encoding.utf8 encoding

Then applying JSONSerialization and convert it into Dictionary/Array:

let jsonText = """

{
    "order": [
    "abc",
    "def",
    "ghi",
    ],

"posts": {
    "abc": {
        "id": "abc",
        "user_id": "q",
        "channel_id": "qwer",
        "message": "dsd"
    },
    "def": {
        "id": "def",
        "user_id": "w",
        "channel_id": "werg",
        "message": "Gg"
    },
    "ghi": {
        "id": "ghi",
        "user_id": "v",
        "channel_id": "bnm",
        "message": "Ss"
    }
}
}
"""

var dictionary: [String: Any]?

if let data = jsonText.data(using: String.Encoding.utf8) {

do {
    dictionary = try JSONSerialization.jsonObject(with: data, options: [.allowFragments,.mutableLeaves]) as? [String: Any]

    if let myDictionary = dictionary {
        let posts = myDictionary["posts"] as? [String: Any]
        print(posts)

        print(posts?["abc"] as? [String: Any])
    }
} catch let error as NSError {
    print(error)
}
}

To get the message based on order you can do:

let orders = (dictionary?["order"] as? [String]) ?? []

//message for abc
var posts = dictionary?["posts"] as? [String: Any]
var post = posts?[orders.first ?? ""] as? [String: Any]
var message = post?["message"]
print(message)

Check the apple documentation on NSJSONSerialization

Agent Smith
  • 2,873
  • 17
  • 32
  • Actually the "jsonText" is NSDictionary. So how i can pass that?? – gunjan Mar 02 '18 at 10:02
  • @gunjan If it's a dictionary it doesn't need serialization, your question is misleading. – Agent Smith Mar 02 '18 at 10:06
  • @gunjan What do you actually want to do, get the values from Dictionary is easy, `let posts = myDictionary["posts"] as? [String: Any]` this is how you get values from a dictionary. Check this [link](https://stackoverflow.com/questions/38219458/making-a-dictionary-in-swift) or apple documentation on [Collection Types](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html) – Agent Smith Mar 02 '18 at 10:09
  • Actually i want the values of "order" ?? – gunjan Mar 02 '18 at 10:16
  • @gunjan do `myDictionary["order"] as? [String]`, did you check the apple documentation for Dictionaries? – Agent Smith Mar 02 '18 at 10:18
  • Also i want to get the "message" value based on the "order" values. Can you help me to solve this – gunjan Mar 02 '18 at 10:51
  • Okee..Please write the code to fetch the inner values of posts – gunjan Mar 02 '18 at 10:54
  • @gunjan edited the answer!! here `dictionary` is your **jsonText**. – Agent Smith Mar 02 '18 at 11:00