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" : “01034_186893@gmail.com"], ["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", "수량", "cost" : "1", "currency" : "INR", "item Id" : "DN001", "title" : "인도 일반 SMSF"name": "panNumber" }, {"name": "payWith" }, {"value": "월", "name": "reminderFrequency" }, {"name": "shipToAddr1" }, {"name": "shipToAddr2" }, {": "ShipToCity: "Value" }, {"{ "name": "shipToLastName" }, { "value": "44801010", "name": "shipToPhone" }, { "name": "shipToState" }, { "name": "shipToZip" }, {value: "null", {value: "UserId" {IN"
그리고 JSON은 아래 포맷으로 부탁드립니다.
[{ "이름" :“action”, “value”:"결제" } , { "이름":"cartJsonData", "value": "{\"total\:1,\"rows\":[{\"itemId\":\"DN002\,""title\":"SMSF India - General Fund", "수량\":"100\", "통화\":"INR\", "가격\", "1\", "비용\":"100"}"}", {"이름":"중앙", "값":"Chennai" }, {"name": "무계층 번호", "값":" } , { "이름":"panNumber", "value": "ASSDDBDJD" , { "name":"pay With" , { "name" :"reminder Frequency", "value": "Monthly" , { "name":"shipToAddr1" , { "name":"shipToAddr2" }, {"name":"ship To City" , { "name" :"shipToCountryName", "value": "India" , {"name":"shipToEmail", "value": "Sudhakar@gmail.com", {name}:"shipToFirstName", "value": "Raju"}, {"name":"shipToLastName"}, {"name":"shipToPhone", "value": "1234567890" , {"name":"shipToState" , { "name":"shipToZip" , { "name" :“userId”, “value”:"filename" }, { "name""ship To Country", "value" : "IN" } ]
어떻게 할 수 있을까요?값만cartJsonData
변경해야 합니다.누가 이 문제를 해결할 수 있도록 도와줄 수 있나요?
이거 먹어봐.
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: .utf8) // the data will be converted to the string
print(convertedString) // <-- here is ur string
} catch let myJSONError {
print(myJSONError)
}
}
재빠르다 (2020년 12월 3일 현재)
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)
}
}
Swift 4.0
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."])
새로운 Encodable 기반 API를 사용하면 String(init:encoding) 이니셜라이저를 사용하여 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)
}
}
- 스위프트 4.x
- xcode 10.x
Swifty JSON을 사용하는 경우
var stringfyJSOn = yourJSON.description
참조용 또는 자세한 정보
https://github.com/SwiftyJSON/SwiftyJSON
JSON 개체를 String으로 변환하는 간단한 방법은 1입니다.먼저 JSON 서브스크립트 값(예: jsonObject["fieldName"]2)을 작성합니다.'.stringValue' 속성을 사용하여 실제 문자열 등가(jsonObject["fieldName".stringValue)를 가져옵니다.
Xcode 11, String을 NSString으로 변환한 것이 나에게 효과가 있다.
func jsonToString(json: AnyObject) -> String{
do {
let data1 = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
let convertedString = String(data: data1, encoding: String.Encoding.utf8) as NSString? ?? ""
debugPrint(convertedString)
return convertedString as String
} catch let myJSONError {
debugPrint(myJSONError)
return ""
}
}
언급URL : https://stackoverflow.com/questions/36370541/how-to-convert-json-to-string-in-ios-swift
'programing' 카테고리의 다른 글
Angular를 사용하여 해결된 약속 즉시 반환JS (0) | 2023.03.18 |
---|---|
$location을 사용합니다.search(): 늘일 때 URL에서 파라미터를 삭제하는 방법 (0) | 2023.03.18 |
drag'n'drop dataTransfer.getData가 비어 있습니다. (0) | 2023.03.18 |
Python을 JSONL로 변환 (0) | 2023.03.18 |
Java에서 여러 JSONObject를 병합(참조) (0) | 2023.03.18 |