如何从 API 解析 JSON [重复]

Posted

技术标签:

【中文标题】如何从 API 解析 JSON [重复]【英文标题】:How Parse JSON from API [duplicate] 【发布时间】:2017-04-06 02:52:04 【问题描述】:

我知道很多这样的问题。我已经在搜索但与我的问题不匹配。

好吧,我会试着用我的代码解释一下

我有这样的数据 API

["profile": 
accountId = 58e470a0c50472851060d083;
androidDeviceId = "[\"3453247ddcf3f809\"]";
androidVersion = 21;
appId =     (
    "c46b4c10-62ce-11e6-bdd4-59e4df4b8410",
    "fac915f0-fe2b-11e6-9dfb-55339bd7be35"
);
appVersion = "v5.1.0";
avatar = "https://account.8villages.com/uploads/images/5/1491366164_bnx1t0rudi.jpg";
birthDate = "12/03/1994";
"channel-group" = android;
communityId = 553e09b251906884443eff85;
coordinates =     
    coordinates =         (
        "106.9602383333333",
        "-6.249333333333334"
    );
    type = Point;
;
crop = "";
crops = "<null>";
customerId = 5369bd85cae84d0e03246a7c;
dateSubmitted =     
    iso = "2017-04-05T04:20:48.483Z";
    timestamp = 1491366048;
;
fullName = "Megi Fernanda";
gender = "Laki-laki";
homeAddress = Payakumbuah;
location = "Kota Payakumbuh";
moderation =     
    at =         
        iso = "2017-04-05T04:20:48.483Z";
        timestamp = 1491366048;
    ;
    by = auto;
    status = moderated;
;

skill = "Budidaya pertanian";
state = "Sumatera Barat";
storeType = "";
subdistrict = "Payakumbuh Barat";
totalConversations =     
    articles = 0;
    forums = 0;
    questions = 2;
    responses = 0;
    storeItems = 1;
;
type = users;
university = "Politeknik Negeri Pertanian Payakumbuh";
, "accessToken": 
key = "lH5aYvnp2JAZ6zoKQK4mpfsxCI0.";
secret = "yfZfTZbsaVIhKCbksGHQnPcPg9mKtoRAKyvjg_cgMeo.";
]

我已经可以得到全名、地址、技能状态等

if let profile = json["profile"] as? NSDictionary 
         let name = profile["fullName"]
         let alamat = profile["Skill"]
 

但我不知道如何在 totalConversation 中获取属性,例如 question、storeItems、points

skill = "Budidaya pertanian";
state = "Sumatera Barat";
storeType = "";
subdistrict = "Payakumbuh Barat";
totalConversations =     
    articles = 0;
    forums = 0;
    questions = 2;
    responses = 0;
    storeItems = 1;
;

我试过了

让 profile = json["profile"]["totalConversation"] 为? NSDictionary

错误标志:输入“任何?”没有下标成员

【问题讨论】:

欺骗。搜索“输入“任何?”没有下标成员”在这里出现了超过 150 次点击。 【参考方案1】:

您收到该错误是因为json["profile"]Any 类型并且它没有任何subscript。所以你需要将json["profile"] 转换为字典,[String: Any] 在 Swift 中是字典类型。

if let profile = json["profile"] as? [String: Any] 
    if let totalConversations = profile["totalConversations"] as? [String: Any] 
        let questions = totalConversations["questions"] as? Int
    

【讨论】:

yaaap 这是工作。我之前已经试过了

以上是关于如何从 API 解析 JSON [重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Swift 2 + XCode 7 + iOS 9 获取和解析 JSON [重复]

从 YouTube API 解析 JSON

如何从Request.Properties [“MS_QueryNameValuePairs”]解析json键值到对象C# [重复]

如何从承诺中获取 JSON [重复]

如何从 Spotify Search API 获取数据并将其解析为 JSON? [在 node.js 中

我应该如何使用 python 从 api 解析这个 JSON? Python 返回 json.decoder.JSONDecodeError: Expecting value: line 1 colu