Programing

JSON 문자열을 NSDictionary로 역 직렬화하려면 어떻게해야합니까?

lottogame 2020. 6. 10. 23:09
반응형

JSON 문자열을 NSDictionary로 역 직렬화하려면 어떻게해야합니까? (iOS 5 이상인 경우)


내 iOS 5 앱 NSString에는 JSON 문자열이 포함되어 있습니다. JSON 문자열 표현을 기본 NSDictionary객체 로 직렬화 해제하고 싶습니다 .

 "{\"password\" : \"1234\",  \"user\" : \"andreas\"}"

나는 다음과 같은 접근법을 시도했다.

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:@"{\"2\":\"3\"}"
                                options:NSJSONReadingMutableContainers
                                  error:&e];  

그러나 런타임 오류가 발생합니다. 내가 무엇을 잘못하고 있지?

-[__NSCFConstantString bytes]: unrecognized selector sent to instance 0x1372c 
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[__NSCFConstantString bytes]: unrecognized selector sent to instance 0x1372c'

NSString매개 변수를 전달 해야하는 곳 에서 매개 변수를 전달하는 것처럼 보입니다 NSData.

NSError *jsonError;
NSData *objectData = [@"{\"2\":\"3\"}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                      options:NSJSONReadingMutableContainers 
                                        error:&jsonError];

NSData *data = [strChangetoJSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data
                                                             options:kNilOptions
                                                               error:&error];

예를 들어 strChangetoJSON NSString에는 특수 문자가 NSString있습니다. 그런 다음 위 코드를 사용하여 해당 문자열을 JSON 응답으로 변환 할 수 있습니다.


@Abizern answer에서 카테고리를 만들었습니다.

@implementation NSString (Extensions)
- (NSDictionary *) json_StringToDictionary {
    NSError *error;
    NSData *objectData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&error];
    return (!json ? nil : json);
}
@end

이렇게 사용하세요

NSString *jsonString = @"{\"2\":\"3\"}";
NSLog(@"%@",[jsonString json_StringToDictionary]);

Swift 3 및 Swift 4 String에는이라는 메소드가 data(using:allowLossyConversion:)있습니다. data(using:allowLossyConversion:)다음과 같은 선언이 있습니다.

func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?

주어진 인코딩을 사용하여 인코딩 된 문자열 표현이 포함 된 데이터를 반환합니다.

스위프트 4, String'들 data(using:allowLossyConversion:)과 함께 이용 될 수 JSONDecoderdecode(_:from:)사전에 JSON 문자열을 직렬화하기 위해.

또한, 신속한 3 스위프트 4, String'들 data(using:allowLossyConversion:)도 함께 함께 이용 될 수 JSONSerializationjson​Object(with:​options:​)사전에 JSON 문자열을 직렬화하기 위해.


#1. 스위프트 4 솔루션

Swift 4 JSONDecoder에는이라는 메소드가 decode(_:from:)있습니다. decode(_:from:)다음과 같은 선언이 있습니다.

func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable

주어진 JSON 표현에서 주어진 유형의 최상위 값을 디코딩합니다.

사용하는 방법을 보여줍니다 아래의 놀이터 코드 data(using:allowLossyConversion:)decode(_:from:)순서는 얻을 수 DictionaryJSON에서 포맷 String:

let jsonString = """
{"password" : "1234",  "user" : "andreas"}
"""

if let data = jsonString.data(using: String.Encoding.utf8) {
    do {
        let decoder = JSONDecoder()
        let jsonDictionary = try decoder.decode(Dictionary<String, String>.self, from: data)
        print(jsonDictionary) // prints: ["user": "andreas", "password": "1234"]
    } catch {
        // Handle error
        print(error)
    }
}

# 2. 스위프트 3 및 스위프트 4 솔루션

With Swift 3 and Swift 4, JSONSerialization has a method called json​Object(with:​options:​). json​Object(with:​options:​) has the following declaration:

class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any

Returns a Foundation object from given JSON data.

The Playground code below shows how to use data(using:allowLossyConversion:) and json​Object(with:​options:​) in order to get a Dictionary from a JSON formatted String:

import Foundation

let jsonString = "{\"password\" : \"1234\",  \"user\" : \"andreas\"}"

if let data = jsonString.data(using: String.Encoding.utf8) {
    do {
        let jsonDictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String : String]
        print(String(describing: jsonDictionary)) // prints: Optional(["user": "andreas", "password": "1234"])
    } catch {
        // Handle error
        print(error)
    }
}

Using Abizern code for swift 2.2

let objectData = responseString!.dataUsingEncoding(NSUTF8StringEncoding)
let json = try NSJSONSerialization.JSONObjectWithData(objectData!, options: NSJSONReadingOptions.MutableContainers)

참고URL : https://stackoverflow.com/questions/8606444/how-do-i-deserialize-a-json-string-into-an-nsdictionary-for-ios-5

반응형