菜鸟教程小白 发表于 2022-12-11 18:23:58

ios - 在 swift 中将 JSON 转换为 ManagedObject 以获取可选参数


                                            <p><p>我有以下格式的 json 数据:</p>

<pre><code>{
    &#34;AvailToDate&#34;: &#34;2016-12-31 00:00:00.0&#34;,
    &#34;CompanyName&#34;: &#34;Google&#34;,
    &#34;ShowroomName&#34;: &#34;Mobile Phones&#34;,
    &#34;OwnerUserId&#34;: &#34;OID1544234&#34;,
    &#34;PartyId&#34;: &#34;APL026306123&#34;,
    &#34;Currency&#34;: &#34;USD&#34;,
    &#34;ProductCount&#34;: 10,
    &#34;AvailFromDate&#34;: &#34;2016-12-20 00:00:00.0&#34;,
    &#34;MaxPrice&#34;: 10,
    &#34;MinPrice&#34;: 1,
    &#34;ShowroomId&#34;: 11904,
    &#34;AccessStatus&#34;: &#34;Open&#34;
}
</code></pre>

<p>我能够将上述对象数组转换为 Dictionary 对象数组。然后我将字典对象转换为核心数据实体。</p>

<p>这是我将 Dictionary 对象转换为 ManagedObject 的代码</p>

<pre><code>let showroom = Showroom(context: bgContext)

showroom.availableFromDate = (tShowroom as? String)?.toDate()
showroom.minPrice = tShowroom as? Float
showroom.showroomID = tShowroom as! Int32
showroom.accessStatus = tShowroom as? String
showroom.availableToDate = (tShowroom as? String)?.toDate()
showroom.companyName = tShowroom as? String
showroom.showroomName = tShowroom as? String
showroom.ownerID = tShowroom as? String
showroom.partyID = tShowroom as? String
showroom.currency = tShowroom as? String
showroom.productsCount = tShowroom as! Int32
showroom.maxPrice = tShowroom as? Float
</code></pre>

<p>如果某些参数缺少JSON接收,我们如何解析对象。我是否必须将 ManagedObject 中的所有参数设置为可选?
我不想对每个参数都使用“if let”或“guard”。实现它的最佳方法是什么?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>您可以简单地使用 <code>??</code> 语法为变量添加“默认值”</p>

<p>假设您想将最低价格设置为 10.2,如果 json 没有返回值,请这样做:</p>

<pre><code>showroom.minPrice = tShowroom as? Float ?? 10.2
</code></pre>

<p>或者对于字符串:</p>

<pre><code>showroom.accessStatus = tShowroom as? String ?? &#34;Default String&#34;
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 在 swift 中将 JSON 转换为 ManagedObject 以获取可选参数,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/41313157/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/41313157/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 在 swift 中将 JSON 转换为 ManagedObject 以获取可选参数