2016-04-08 11 views
8

में JSON स्ट्रिंग में एक साधारण स्ट्रिंग को कनवर्ट करें मुझे पता है कि एक ही शीर्षक here के साथ एक प्रश्न है। लेकिन उस सवाल में, वह एक शब्दकोश को जेएसओएन में बदलने की कोशिश कर रहा है। लेकिन मेरे पास एक साधारण स्टिंग है: "बाग"स्विफ्ट

और मुझे इसे JSON के रूप में भेजना होगा। मैंने स्विफ्टजसन की कोशिश की है लेकिन फिर भी मैं इसे JSON में रूपांतरित करने में असमर्थ हूं।

अंतिम पंक्ति में मेरे कोड दुर्घटनाओं:

fatal error: unexpectedly found nil while unwrapping an Optional value 

मैं कुछ गलत कर रहा हूँ

यहाँ मेरी कोड है?

उत्तर

18

JSON has to be an array or a dictionary, यह केवल एक स्ट्रिंग नहीं हो सकता है।

मैं आप इसे में अपने स्ट्रिंग के साथ एक सरणी बनाने की सलाह:

let array = ["garden"] 

तो फिर तुम इस सरणी से एक JSON वस्तु बनाने:

if let json = try? NSJSONSerialization.dataWithJSONObject(array, options: []) { 
    // here `json` is your JSON data 
} 

आप के बजाय एक स्ट्रिंग के रूप में इस JSON की जरूरत है डेटा आप इस का उपयोग कर सकते हैं:

if let json = try? NSJSONSerialization.dataWithJSONObject(array, options: []) { 
    // here `json` is your JSON data, an array containing the String 
    // if you need a JSON string instead of data, then do this: 
    if let content = String(data: json, encoding: NSUTF8StringEncoding) { 
     // here `content` is the JSON data decoded as a String 
     print(content) 
    } 
} 

प्रिंटों:

[ "उद्यान"]

आप एक शब्दकोश के बजाय एक सरणी होने पसंद करते हैं, का पालन ही विचार: तो शब्दकोश बनाने परिवर्तित।

let dict = ["location": "garden"] 

if let json = try? NSJSONSerialization.dataWithJSONObject(dict, options: []) { 
    if let content = String(data: json, encoding: NSUTF8StringEncoding) { 
     // here `content` is the JSON dictionary containing the String 
     print(content) 
    } 
} 

प्रिंटों:

{ "स्थान": "उद्यान"}

1

स्विफ्ट 3 संस्करण:

let location = ["location"] 
    if let json = try? JSONSerialization.data(withJSONObject: location, options: []) { 
     if let content = String(data: json, encoding: .utf8) { 
      print(content) 
     } 
    }