简体   繁体   中英

How to parse array of strings in swift?

I am writing a simple full stack app and I made the return from the backend to be, in certain cases, just like an array of strings like below:

["one","two","three"]

The problem I am having now is that this return can't be parsed in swift like usual JSON data. I searched but found nothing. What I am trying to do is :

let json = try JSONSerialization.jsonObject(with: data!, options: [.mutableContainers, .allowFragments]) as? [String]

Unfortunately, this doesn't work at all How can I parse this just like a normal array?

Thanks in advance.

UPDATE: I am adding some more relevant code below:

let task = URLSession.shared.dataTask(with: request as URLRequest){
        data, response, error in {
            do {
                let json =  try JSONSerialization.jsonObject(with: data!, options: [.mutableContainers, .allowFragments]) as? [String]
                print(json)
            }catch{
                print(error)
            }
 }
datatask.resume()

The error I am getting in the console is "Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}"

Thanks for all of you.

If you're getting the 3840 error , then the JSON is not valid JSON, period.

The JSON string equivalent of the array is supposed to be

let jsonString = "[\"one\",\"two\",\"three\"]"

The Swift 4 literal multiline syntax shows the actual format without the escaping backslashes

let jsonString = """
["one","two","three"]
"""

You are able to parse it without any options ( no .allowFragments , and no .mutableContainers )

let data = Data(jsonString.utf8)
do {
    let array = try JSONSerialization.jsonObject(with: data) as! [String]
    print(array) // ["one", "two", "three"]
} catch {
    print(error)
}

Almost everybody misuses the JSONSerialization Reading Options

  • .allowFragments is only needed if the root object is not array and not dictionary
  • .mutableContainers is completely meaningless in Swift

In 99% of the cases you can omit the options parameter

You have to give proper JSON response as data. After that, JSON serialisation will work properly. Your JSON response should be like this:

{
  "array": [
    "one",
    "two",
    "three"
  ]
}

let json =  try JSONSerialization.jsonObject(with: data!, options: [.mutableContainers, .allowFragments]) as? [String]
                print(json)

After that in above line you will your array response like this one - http://jsoneditoronline.org/?id=eafd7ff34b45b2a380ebbe5959607906

Update ####

Your response starts with array and it contains dictionary see below code for your example

    let jsonString = """
[{"Name":"one"},{"Name":"two"},{"Name":"three"}]
"""

if let jsonData = jsonString.data(using: .utf8)
{
    let json =  try JSONSerialization.jsonObject(with: jsonData, options: [.mutableContainers, .allowFragments]) as? [[String:String]]
    print(json)
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM