菜鸟教程小白 发表于 2022-12-11 18:00:07

ios - swift 3,JSON,编写时顶级类型无效


                                            <p><p>我有两个完全正确的 json 对象,一个是从函数创建的,另一个是硬编码的,硬编码的一个有效,另一个无效(它总是提示错误 <code>invalid top-level type</code> ,这很奇怪。任何提示?Tks</p>

<pre><code>let myData = self.dailyMileage?.toDictionary()

let directData = [&#34;orgId&#34; : self.orgId, &#34;driverId&#34; : self.driverId, &#34;date&#34; : Utils.getTodaysDate() ] as

//this won&#39;t work unless I substitute myData with directData                        
let jsonData = try JSONSerialization.data(withJSONObject: myData, options: .prettyPrinted)

//this is the function that produces myData, and nothing is nil
public func toDictionary() -&gt; {
    let dict = [ &#34;orgId&#34; : orgId , &#34;driverId&#34;: driverId, &#34;date&#34; : date] as
    return dict
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p>文档中给出的 <p><code>JSONSerialization</code>:</p>
<blockquote>
<p>An object that may be converted to JSON must have the following properties:</p>
<p>The top level object is an NSArray or NSDictionary. All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.</p>
<p>All dictionary keys are instances of NSString. Numbers are not NaN or infinity.</p>
<p>Other rules may apply. Calling isValidJSONObject(_:) or attempting a conversion are the definitive ways to tell if a given object can be converted to JSON data.</p>
</blockquote>
<ol>
<li><p>我认为来自函数的那个​​可能有一个 NSDate 对象而不是一个 NSString 对象。</p>
</li>
<li><p>另一个原因是因为您的 <code>myData</code> 对象是可选的。 <code>JSONSerialization</code> 可能会出现错误,例如对象是可选的。</p>
</li>
</ol>
<p>请检查是否是由于这两个原因之一。随时提出修改建议以使其变得更好。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - swift 3,JSON,编写时顶级类型无效,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/40453343/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/40453343/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - swift 3,JSON,编写时顶级类型无效