web-dev-qa-db-ja.com

iOS SwiftでJSONを文字列に変換する方法は?

以下は、以下のJSON出力のコードです。

let params : [[String : AnyObject]]  = [["name" : "action", "value" : "pay" ],["name" : "cartJsonData" , "value" : ["total": 1,"rows":[["quantity": “1” ,"title":"Donation for SMSF India - General Fund","price":"1","itemId":"DN001","cost": “1”,”currency":"INR"]]]], ["name" : "center", "value" : "Chennai"], ["name" : "flatNumber", "value" : "503"], ["name" : "panNumber", "value" : ""], ["name" : "payWith"], ["name" : "reminderFrequency","value" : "Monthly"],  ["name" : "shipToAddr1"], ["name" : "shipToAddr2"], ["name" : "shipToCity"], ["name" : "shipToCountryName" , "value" : "India"], ["name" : "shipToEmail", "value" : “[email protected]"], ["name" : "shipToFirstName" , "value": "4480101010"], ["name" : "shipToLastName"], ["name" : "shipToPhone", "value" : "4480101010"], ["name" : "shipToState"], ["name" : "shipToZip"], ["name" : "userId", "value" : “null”], ["name" : "shipToCountry", "value" : "IN"]]

var jsonObject: NSData? = nil

do {
   jsonObject = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())
   print(jsonObject) // This will print the below json. 
} 
catch{}

JsonObjectを印刷することで、これを取得しました。

[{"value": "pay"、 "name": "action"}、{"value":{"rows":[{"price": "1"、 "quantity": "1"、 "cost" :「1」、「通貨」:「INR」、「itemId」:「DN001」、「タイトル」:「SMSFインドへの寄付-一般基金」}]、「合計」:1}、「名前」:「cartJsonData "}、{" value ":" Chennai "、" name ":" center "}、{" value ":" 503 "、" name ":" flatNumber "}、{" value ":" "、" name " : "panNumber"}、{"name": "payWith"}、{"value": "Monthly"、 "name": "reminderFrequency"}、{"name": "shipToAddr1"}、{"name": " shipToAddr2 "}、{" name ":" shipToCity "}、{" value ":"インド "、" name ":" shipToCountryName "}、{" value ":" [email protected] "、" name ":" shipToEmail "}、{" value ":" 4480101010 "、" name ":" shipToFirstName "}、{" name ":" shipToLastName "}、{" value ":" 4480101010 "、" name ":" shipToPhone "}、 {"name": "shipToState"}、{"name": "shipToZip"}、{"value": "null"、 "name": "userId"}、{"value": "IN"、 "name" : "shipToCountry"}]

また、JSONを以下の形式にする必要があります。

[{“ name”:“ action”、“ value”:“ pay”}、{“ name”:“ cartJsonData”、“ value”:“ {\” total \”:1、\” rows \”:[{\"itemId \":\ "DN002 \"、\ "title \":\ "SMSF Indiaへの寄付-一般基金\"、\ "quantity \":\ "100 \"、\ "currency \":\ " INR \”、\” price \”:\” 1 \”、\” cost \”:\” 100 \”}]}”}、{“ name”:“ center”、“ value”:“ Chennai”} 、{“ name”:“ flatNumber”、“ value”:““}、{“ name”:“ panNumber”、“ value”:“ ASSDDBBDJD”}、{“ name”:“ payWith”}、{“ name” :“ reminderFrequency”、“ value”:“ Monthly”}、{“ name”:“ shipToAddr1”}、{“ name”:“ shipToAddr2”}、{“ name”:“ shipToCity”}、{“ name”:“ shipToCountryName」、「value」:「India」}、{「name」:「shipToEmail」、「value」:「[email protected]」}、{「name」:「shipToFirstName」、「value」:「Raju」 }、{“ name”:“ shipToLastName”}、{“ name”:“ shipToPhone”、 “値”:“ 1234567890”}、{“名前”:“ shipToState”}、{“名前”:“ shipToZip”}、{“名前”:“ userId”、“値”:“ null”}、{“名前」:「shipToCountry」、「value」:「IN」}]

どうすればできますか? cartJsonDataの値のみを変更する必要があります。誰かがこれを解決するのを手伝ってくれますか?

20
Divya Ponnuraj

これを試して。

func jsonToString(json: AnyObject){
        do {
          let data1 =  try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted) // first of all convert json to the data
            let convertedString = String(data: data1, encoding: NSUTF8StringEncoding) // the data will be converted to the string
            print(convertedString) // <-- here is ur string  

        } catch let myJSONError {
            print(myJSONError)
        }

    }
34
ak sacha

Swift 4.

static func stringify(json: Any, prettyPrinted: Bool = false) -> String {
    var options: JSONSerialization.WritingOptions = []
    if prettyPrinted {
      options = JSONSerialization.WritingOptions.prettyPrinted
    }

    do {
      let data = try JSONSerialization.data(withJSONObject: json, options: options)
      if let string = String(data: data, encoding: String.Encoding.utf8) {
        return string
      }
    } catch {
      print(error)
    }

    return ""
}

使用法

stringify(json: ["message": "Hello."])
9
Minh Hoang

Swift(2018年7月10日現在)

func jsonToString(json: AnyObject){
    do {
        let data1 =  try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted) // first of all convert json to the data
        let convertedString = String(data: data1, encoding: String.Encoding.utf8) // the data will be converted to the string
        print(convertedString ?? "defaultvalue")
    } catch let myJSONError {
        print(myJSONError)
    }

}
9
BennyTheNerd

新しいEncodableベースのAPIを使用して、String(init:encoding)initialiserを使用してJSONファイルの文字列バージョンを取得できます。私はこれをプレイグラウンドで実行し、最後の印刷ステートメントは私に与えました

json {"year":1961,"month":4}

このフォーマットでは、詳細に最小数の文字が使用されているようです。

struct Dob: Codable {
    let year: Int
    let month: Int
}

let dob = Dob(year: 1961, month: 4)
print("dob", dob)

if let dobdata = try? JSONEncoder().encode(dob) {
    print("dobdata base64", dobdata.base64EncodedString())
    if let ddob = try? JSONDecoder().decode(Dob.self, from: dobdata) {
        print("resetored dob", ddob)
    }
    if let json = String(data: dobdata, encoding: .utf8) {
      print("json", json)
    }
}
1
MarkAurelius