如何在swift中将JSON字符串转换为JSON对象?

时间:2017-06-17 10:24:35

标签: ios json swift swift3

我尝试生成JSON对象并将其转换为JSON String,并且该进程已成功放置。但是当我尝试将JSON String转换为JSON对象时,我的真正问题就出现了。当我尝试时,我得到的结果为零。

func generateJSONObject() {
        let jsonObject = createJSONObject(firstName: firstName[0], middleName: middleName[0], lastName: lastName[0], age: age[0], weight: weight[0])
        print("jsonObject : \(jsonObject)")

        let jsonString = jsonObject.description // convert It to JSON String
        print("jsonString : \(jsonString)")

        let jsonObjectFromString = convertToDictionary(text: jsonString)
        print("jsonObjectFromString : \(String(describing: jsonObjectFromString))")

    }

createJSONObject func

// JSON Object creation
    func createJSONObject(firstName: String, middleName: String, lastName: String, age: Int, weight: Int) -> [String: Any] {

        let jsonObject: [String: Any] = [
            "user1": [
                "first_name": firstName,
                "middle_name": middleName,
                "last_name": lastName,
                "age": age,
                "weight": weight
            ]
        ]
        return jsonObject
    }

convertToDictionary func

func convertToDictionary(text: String) -> [String: Any]? {
        if let data = text.data(using: .utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
            } catch {
                print(error.localizedDescription)
            }
        }
        return nil
    }

日志

  1. 当我打印JSON对象时,我
  2. jsonObject:[" user1":[" age":21," middle_name":" Lazar"," last_name& #34;:" V","体重":67," first_name":" Alwin"]]

    1. 当我打印JSON字符串时,我得到了

      jsonString:[" user1":[" age":21," middle_name":" Lazar"," last_name& #34;:" V","体重":67," first_name":" Alwin"]]

    2. JSON字符串转换为JSON对象,我得到以下错误

      无法读取数据,因为格式不正确。

      jsonObjectFromString:nil

    3. 我不知道为什么会这样。我想将JSON字符串转换为JSON对象,我想解析JSON

2 个答案:

答案 0 :(得分:2)

基于讨论

import Foundation

let firstName = "Joe"
let lastName = "Doe"
let middleName = "Mc."
let age = 100
let weight = 45

let jsonObject: [String: [String:Any]] = [
    "user1": [
        "first_name": firstName,
        "middle_name": middleName,
        "last_name": lastName,
        "age": age,
        "weight": weight
    ]
]
if let data = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted),
    let str = String(data: data, encoding: .utf8) {
    print(str)
}

打印

{
  "user1" : {
    "age" : 100,
    "middle_name" : "Mc.",
    "last_name" : "Doe",
    "weight" : 45,
    "first_name" : "Joe"
  }
}

答案 1 :(得分:0)

Json必须在Array或Dictionary中,它不能只是字符串所以要创建一个jsonstring首先需要转换为Data格式然后转换为String

 symbol | day            | price  |     updated_at      
--------+----------------+--------+---------------------
 FOX    | 2017-06-02     | 100.00 | 2017-06-02 15:00:00 
 FOX    | 2017-06-03     | 777.00 | 2017-06-03 15:30:00
 FOX    | 2017-06-04     | 777.00 | 2017-06-03 15:30:00 -- price from 3rd
 BEE    | 2017-06-01     |   6.10 | 2017-06-01 18:00:00
 BEE    | 2017-06-02     |   6.20 | 2017-06-02 17:00:00
 BEE    | 2017-06-03     |   6.30 | 2017-06-03 17:00:00
 BEE    | 2017-06-04     |   6.30 | 2017-06-03 17:00:00 -- price from 3rd