\/

2014-11-21 3 views
8

으로 NSDictionary를 json string으로 바꾸는 문제가 NSDictionary를 json string.everything으로 변환하려고합니다. 다음과 같이 설명 된 작은 문제가 있습니다. 다음 변환 코드가 있습니다./

{ 
    "hello" : "21\/11\/2014 10:07:42 AM" 
} 
:

NSLog(@"%@", [self dictToJson:@{@"hello" : @"21/11/2014 10:07:42 AM"}]); 

다음이 NSLog의 출력은 다음과 같습니다는 NSString에있는 NSDictionary :로

-(NSString *)dictToJson:(NSDictionary *)dict 
{ 
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil]; 
    return [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding]; 
} 

나는 메서드를 호출하고 I 출력을 다음 기대하고

, 내가 어떻게 그것을 달성 할 수

{ 
     "hello" : "21/11/2014 10:07:42 AM" 
} 

은이 stringByReplacingOccurrencesOfString 방법을 사용하여 수행 할 수 있습니다,하지만 난이 사용하지 않습니다. 같은 것을 성취 할 수있는 다른 방법이 있습니까?

+0

는 뭔가 잘못입니까? –

답변

1

JSON 개체를 String으로 변환하면 슬래시가 이스케이프됩니다. 그래서 백 슬래시가 결과에 추가됩니다.

문자열을 JSON 객체로 다시 변환하고 객체를 기록하면 예상대로 결과를 볼 수 있습니다. 따라서 문자열에 문제가 없는지 확인할 수 있습니다.

0

-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint; 



-(NSString *)dictToJson:(NSDictionary *)dict 
    { 

     NSData *jsonData = [NSJSONSerialization dataWithJSONObject: dict 
                options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0) 
                error:&error]; 

    if (! jsonData) { 
     NSLog(@"bv_jsonStringWithPrettyPrint: error: %@", error.localizedDescription); 
     return @"{}"; 
    } else { 
     return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
    } 

    } 

Generate JSON string from NSDictionary in iOS

2

이 시도 참조

NSData *json = [NSJSONSerialization dataWithJSONObject:dict 
               options:0 
               error:&error]; 
NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding]; 
// This will be the json string in the preferred format 
jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"]; 

// And this will be the json data object 
NSData *processedData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; 
21

있는 NSDictionary를 추가 -에 - 문자열

NSError * err; 
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:response options:0 error:&err]; 
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 

문자열 -에 - 그냥 사전에있는`description` 메서드를 호출하는 경우 NSDictionary에

NSError * err; 
NSDictionary * response = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:[NSData dataFromString:str] options:NSJSONReadingMutableContainers error:&err];