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

时间:2017-11-01 18:19:33

标签: json swift string struct swift4

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

字符串

<macrodef name="test">
<attribute name="attribute1"/> 

<element name="X"/> 
<element name="MandatoryX" optional="true/>

<sequential>
<local>
<!--here check if the element <MandatoryX/> is passed and if Yes than make sure that element X is passed too-->  
</local>
</sequential>
</macrodef>

<test attribute1="1">
<!--Here MandatoryX is missing and X can be missing too-->
</test>

or

<test attribute1="1">
<MandatoryX>In case MandatoryX is present, than element X must be present too</MandatoryX>
<X>Here X is mandatory</X>
</test>

2 个答案:

答案 0 :(得分: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)")
}

答案 1 :(得分:-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);