【问题标题】:How to append strings in for each loop in swift如何在swift中为每个循环附加字符串
【发布时间】:2019-10-21 06:45:15
【问题描述】:

我想解析 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
            }

        }
    } 

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

【问题讨论】:

  • 你的意思是数据在记录内乱序,还是记录本身乱序?如果是前者,那么您要么需要使用不同的数据结构,因为字典没有顺序,要么使用键以您想要的顺序提取数据。
  • @flanker,数据顺序正确。当我使用字典时,顺序不在序列中。有没有其他机制可以实现这一目标?谢谢。
  • @devan,您是否事先知道密钥是什么,并且总是相同的?或者问题是它们真的不是键和值,而只是一对数据值?
  • @flanker,大部分响应键应该是相同的。可能是一些关键值是否存在取决于要求。但是需要根据响应保持顺序。我认为字典在这种情况下不起作用吧?

标签: ios json swift nsstring


【解决方案1】:

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
  }
}

【讨论】:

    猜你喜欢
    • 2018-10-19
    • 2017-07-10
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 2016-03-31
    相关资源
    最近更新 更多