从Swift 4中的JSON String中间抓取特定值

问题描述 投票:-1回答:2

我想从这个字符串中仅提取链接并使用该链接创建一个新字符串,但我不确定这样做的最佳方法。如果有人能够告诉我如何有效地做到这一点,我将非常感激!

{
    "timestamp": 1509507857555,
    "profileId": "e58d7f751c7f498085a79a37bf22f20b",
    "profileName": "Rhidlor",
    "textures": {
        "SKIN": {
            "url": "http://textures.minecraft.net/texture/1137b867b4a2fb593cf6d05d8210937cc78bc9e0558ad63d41cc8ec2f99e7d63"
        }
    }
}
json swift string struct swift4
2个回答
2
投票

您的给定字符串是JSON。你可以从给定的JSON获取url是这样的:

struct Response: Decodable {
    var textures: [String: Textures]
}
struct Textures: Decodable {
    var url: String
}

let jsonStr = """
{"timestamp":1509507857555,"profileId":"e58d7f751c7f498085a79a37bf22f20b","profileName":"Rhidlor","textures":{"SKIN":{"url":"http://textures.minecraft.net/texture/1137b867b4a2fb593cf6d05d8210937cc78bc9e0558ad63d41cc8ec2f99e7d63"}}}
"""
let data = jsonStr.data(using: .utf8)!
let decoder = JSONDecoder()
do {
    let jsonData = try decoder.decode(Response.self, from: data)
    if let skin = jsonData.textures["SKIN"] {
        print(skin.url)
    }
}
catch {
    print("error:\(error)")
}

-2
投票

您可以使用这些方法在任何String内部获取URL。

Swift4

    let testString: String = "{\"timestamp\":1509507857555,\"profileId\":\"e58d7f751c7f498085a79a37bf22f20b\",\"profileName\":\"Rhidlor\",\"textures\":{\"SKIN\":{\"url\":\"http://textures.minecraft.net/texture/1137b867b4a2fb593cf6d05d8210937cc78bc9e0558ad63d41cc8ec2f99e7d63\"}}}"
    let pat = "http?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?"
    let regex = try! NSRegularExpression(pattern: pat, options: [])
    let matches = regex.matches(in: testString, options: [], range: NSRange(location: 0, length: LGSemiModalNavViewController.characters.count))

    var matchedUrls = [String]()

    for match in matches {
        let url = (htmlSource as NSString).substring(with: match.range)
        matchedUrls.append(url)
    }

    print(matchedUrls)

目标 - C.

  NSString *testString         = @"{\"timestamp\":1509507857555,\"profileId\":\"e58d7f751c7f498085a79a37bf22f20b\",\"profileName\":\"Rhidlor\",\"textures\":{\"SKIN\":{\"url\":\"http://textures.minecraft.net/texture/1137b867b4a2fb593cf6d05d8210937cc78bc9e0558ad63d41cc8ec2f99e7d63\"}}}";

  NSError             *error;
  NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"http?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?" options:NSRegularExpressionCaseInsensitive error:&error];

  NSArray *arrayOfAllMatches = [regex matchesInString:testString options:0 range:NSMakeRange(0, [testString length])];

  NSMutableArray *arrayOfURLs = [NSMutableArray new];

  for ( NSTextCheckingResult *match in arrayOfAllMatches ) {
      NSString *substringForMatch = [testString substringWithRange:match.range];
      NSLog(@"Extracted URL: %@", substringForMatch);

      [arrayOfURLs addObject:substringForMatch];
  }

  NSLog(@"%@",arrayOfURLs);
© www.soinside.com 2019 - 2024. All rights reserved.