如何从VStack列表中的项目创建Json?

时间:2020-05-05 04:43:34

标签: swift swiftui swiftui-list

我具有以下结构

struct ContentView: View {

    @State private var usedWord = [String]()
    @State private var  rootWord = ""
    @State private var newWord = ""

    var manager = HttpRequest()

    var body: some View {
        NavigationView{
            VStack{
                TextField("Enter your symptom", text: $newWord, onCommit: addNewWord)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .autocapitalization(.none )
                    .padding()
                List {
                    ForEach(usedWord, id: \.self){
                    Text($0)
                    }
                    .onDelete(perform: deleteItem)
                }

                Button("Get diagnose"){
                    // here we plac logic of sending request to API server

                }
            }
        .navigationBarTitle(rootWord)
        }
    }

    func addNewWord() {
        let answer = newWord.lowercased( ).trimmingCharacters(in: .whitespacesAndNewlines)
        guard answer.count > 0 else {
            return
        }

        // extra validation to come
        usedWord.insert(answer, at: 0)
        newWord = ""
    }

     func deleteItem(at indexSet: IndexSet) {
        self.usedWord.remove(atOffsets: indexSet)
    }
}

这是其中的文本项列表。在Button(“ Get diagnostic”)中,我想遍历List并创建Json对象以将其发送到API服务器。 Json的结构类似于{'1':'胸痛','2':'头痛'}。我有一个请求函数,但我不知道如何创建Json

1 个答案:

答案 0 :(得分:1)

您不需要遍历list。您应该像这样遍历列表的数据:

Button("Get diagnose"){
    // here we plac logic of sending request to API server
    for word in self.usedWord.enumerated() {
       print(word.offset, ":", word.element)
    }
}

我不知道您如何需要JSON,但是,您可以像这样构建dictionary

let dictionary = Dictionary(uniqueKeysWithValues: zip(self.usedWord.indices, self.usedWord))

JSONData一样:

let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: [])