如何在swift iOS中将JSON转换为字典?

时间:2017-07-21 09:25:35

标签: json swift xcode dictionary

您好我正在制作一个适用于API的应用。我有一个工作代码从API接收数据。但我认为让代码更清洁会更好。我想在字典中设置api中的数据,但我无法使其正常工作。任何帮助将不胜感激,谢谢!

这是api结果: enter image description here

我想在字典中设置AutorId和BranchId等。 这是我现在拥有的代码。 这是Project类:

URL url = new URL("http://demo.url.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
ContentValues values = new ContentValues();
values.put("Authorization", "Basic dGVzdGVyOjEfhdjkejlhMmU4MjNjNDc=");
values.put("Content-Type", "application/x-www-form-urlencoded");
values.put("Body", "{grant_type=client_credentials}");
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
StringBuilder sb = new StringBuilder();
sb.append(URLEncoder.encode("data", "UTF-8"));
sb.append("=");
writer.write(sb.toString());
writer.flush();
writer.close();
os.close();
conn.connect();

}

在这里我试图在字典中设置它:

class Project: NSObject {
var AuthorId: String?
var BranchId: String?
var CompanyId: String?
var ContactId: String?
var Date: String?
var Deadline: String?
var Description: String?
var Id: String?
var State: String?
init(dictionary: [String: Any]) {
    self.AuthorId = dictionary["AuthorId"] as? String
    self.BranchId = dictionary["BranchId"] as? String
    self.CompanyId = dictionary["CompanyId"] as? String
    self.ContactId = dictionary["ContactId"] as? String
    self.Date = dictionary["Date"] as? String
    self.Deadline = dictionary["Deadline"] as? String
    self.Description = dictionary["Description"] as? String
    self.Id = dictionary["Id"] as? String
    self.State = dictionary["State"] as? String

}

0 个答案:

没有答案