ios - 如何在 swift 中的每个循环中附加字符串

标签 ios json swift nsstring

我想解析json字符串并显示在UITextView中。 我正在使用带有键和值的 HTML 字符串获取数据。这是来自服务器的以下示例字符串响应,

   {"":"<strong>Adidas<\/strong><br>Enjoy 10% off","Period":"10 Oct 2019 - 11 Nov 2019","Description":"<p>Enjoy 30% off 
   "Terms & Conditons":"<ol>\n<li>It's available only in peak hours<\/li>\n}

我需要用 HTML 显示如下格式,

Expected output: 
      Adidas
      Enjoy 10% off
      Period:
      10 Oct 2019 - 11 Nov 2019
      Description:
      Enjoy 30% off.
      Terms & Conditons:
      It's available only in peak hours

我使用了字典并提取了数据,但问题是数据的顺序不按顺序。

   func setupData(responseString : String)
   {
    // Convert string to dictionary for extracting the keys and values
    // Need to maintain the order while adding the data
    let content = convertToDictionary(text: responseString)
    var text : String = ""
    if let contentDataDict = content
    {
        for (key, value) in  contentDataDict
        {
         // want to append the key and values in the sequence order
                textView.attributedText = text.htmlToAttributedString
            }

        }
    } 

如何根据预期输出解析和显示数据。

最佳答案

Devan,你的想法是对的,字典不起作用。你最好将 html 加载到数组中。我使用伪代码来表示新的 convertToArray 来替换您的 convertToDictionary,因为您没有提供所有原始代码

struct Component {
  field: String
  value: String
}

func convertToArray(response: String) -> [Component] [
  let components = [Component]()
  for entries in response {
    //extract key/value pairs from html as before
    //then create a component struct with them and add it to the array
    components.append(Component(field: key, value: value)
  }
  return components //now a sequence of structs represent your data in order
}


func setupData(responseString : String) {
  let components: [Component] = convertToArray(text: responseString)
  for component in components {
     //add component.field and component.value to your attributed text string
     //and then display as before
  }
}

关于ios - 如何在 swift 中的每个循环中附加字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58481051/

相关文章:

ios - UISearchBar 在 iOS 8 中隐藏

ios - 需要修复我的复选框 : to change states in one click instead of two clicks. Swift 3, IOS

json - ElasticSearch搜索问题

ios - 无法在 UIStackview 响应式(Reactive)和声明式 swift 中转换类型的值

objective-c - 如何聚焦 Collection View 可见单元格的最后一个单元格?

iphone - 您发现哪些在 ios 开发中有用的优秀第三方工具?

ios - 在 iOS Swift 中将远程 JSON 数据同步到本地缓存存储

javascript - 关于使用 jQuery 和 JSON 在 div 中设置背景...

javascript - Play2.2 Java - 防止 Javascript 模板转义

ios - 使用 swift 创建 TableView