2017-10-20 74 views
-4

我有一个JSON数组一样,如何编码jsonarray上雨燕4 IOS

[ 
    { 
     "value" : "temp", 
     "value2" : "temp2", 
     "value3" : "temp3", 
    }, 
    { 
     "value" : "temp"; 
     "value2" : "temp2", 
     "value3" : "temp3", 
    }, { 
     "value" : "temp", 
     "value2" : "temp2", 
     "value3" : "temp3", 
    } 
] 

我尝试解析上迅速4 iOS应用。 我没有找到关于这个问题的任何解决方案。 我已经尝试了很多代码像

let jsonpars = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as! [AnyObject] 
+5

的字符串无效JSON。 – Aris

+0

请搜索:[有2700多个相关问题](https://stackoverflow.com/search?q=%5Bswift%5D+parse+JSON)。在Swift 4中,你可以使用['JSONDecoder'](https://developer.apple.com/documentation/foundation/jsondecoder) – vadian

+0

就像Aris说的那样,这是错误的JSON格式,所以首先要解决的问题比我们能说的更好 – Ladislav

回答

0

您所提供的JSON是无效的。正确的JSON格式应该是这样的:

  1. 更换的=每次出现:
  2. 用逗号

结果应该是这样的替换每个;

[ 
    { 
     "value":"temp", 
     "value2":"temp2", 
     "value3":"temp3", 
    }, 
    ... 
] 

然后,您提供的解析代码示例应该可以正常工作。

您的示例JSON看起来像解析后打印出来的内容。例如:

let jsonpars = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as! [AnyObject] 

print(jsonpars) 

导致调试版本JSON输出:

[{ 
    value = temp; 
    value2 = temp2; 
    value3 = temp3; 
}, { 
... 
] 

真正 JSON,要分析数据,必须有冒号和逗号。

0

使用quicktype,我产生这种模式和转换代码为您的样品(纠正语法问题后):

import Foundation 

struct Value: Codable { 
    let value, value2, value3: String 
} 

extension Array where Element == Value { 
    static func from(json: String, using encoding: String.Encoding = .utf8) -> [Value]? { 
     guard let data = json.data(using: encoding) else { return nil } 
     return [Value].from(data: data) 
    } 

    static func from(data: Data) -> [Value]? { 
     let decoder = JSONDecoder() 
     return try? decoder.decode([Value].self, from: data) 
    } 

    var jsonData: Data? { 
     let encoder = JSONEncoder() 
     return try? encoder.encode(self) 
    } 

    var jsonString: String? { 
     guard let data = self.jsonData else { return nil } 
     return String(data: data, encoding: .utf8) 
    } 
} 

然后你就可以反序列化这样的:

let values = [Value].from(json: """ 
    [ 
     { 
      "value": "temp", 
      "value2": "temp2", 
      "value3": "temp3" 
     }, 
     { 
      "value": "temp", 
      "value2": "temp2", 
      "value3": "temp3" 
     }, 
     { 
      "value": "temp", 
      "value2": "temp2", 
      "value3": "temp3" 
     } 
    ] 
""")!