菜鸟教程小白 发表于 2022-12-11 20:43:31

ios - 如何在 swift 4 中使用 json 对象发送 json 数据


                                            <p><p>我需要按以下顺序将 json 发送到服务器</p>

<pre><code>data:{&#34;firstname&#34;:&#34;Alpha&#34;,&#34;lastname&#34;:&#34;Beta&#34;}
</code></pre>

<p> <a href="/image/uIYR9.png" rel="noreferrer noopener nofollow"><img src="/image/uIYR9.png" alt="enter image description here"/></a> </p>

<p>在这种情况下,数据键在 <code></code> 之类的 json 之外,但是当我进行序列化时,它将请求作为 </p>

<pre><code>{
&#34;data&#34; : {
    &#34;firstname&#34; : &#34;alpha&#34;,
    &#34;lastname&#34; : &#34;beta&#34;
}
}
</code></pre>

<p>这些是我的模型:</p>

<pre><code>struct UserDetail :Codable {
    let data :CreateProfileModel
}

struct CreateProfileModel :Codable {
    let firstname :String
   let lastname :String
}
</code></pre>

<p>我在这些模型中添加的数据</p>

<pre><code>let profileInfo = CreateProfileModel(firstname: &#34;alpha&#34; , lastname: &#34;beta&#34;)

let userDetails = UserDetail(data: profileInfo)
</code></pre>

<p>这是我使用 swift 进行的 json 编码:</p>

<pre><code> let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = .prettyPrinted
do{
    let userData = try jsonEncoder.encode(userDetails)
   print(String(data: userData, encoding: .utf8)!)
   networkListener.requestPost(endpoint: endpoint, data: userData , headerValue: nil)
   }catch{
    print(error)
   }
</code></pre>

<p>在 requestPost 方法中</p>

<pre><code>func requestPost(endpoint : String , data :Data,headerValue : String?){....
request.httpbody = data
}
</code></pre>

<p>我正在将该数据添加到 <code>request.httpbody</code>。</p>

<p>如何使用 profileInfo 添加数据键? </p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>试试这个代码:</p>

<pre><code>var columnValus:= [:]

columnValus[&#34;firstname&#34;] = userDetails.data.firstname
columnValus[&#34;lastname&#34;] = userDetails.data.lastname

let userData = [
      &#34;data&#34;: columnValus
      ] as

do {
      let postData = try JSONSerialization.data(withJSONObject: userData, options: [])
      networkListener.requestPost(endpoint: endpoint, data: postData , headerValue: nil)
}catch let error as NSError {
      print(error)
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 如何在 swift 4 中使用 json 对象发送 json 数据,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/52985137/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/52985137/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 如何在 swift 4 中使用 json 对象发送 json 数据