JSON 문자열에서 반환된 Objective-C의 null 값 확인
웹 서버에서 전송된 JSON 개체가 있습니다.
로그는 다음과 같습니다.
{
"status":"success",
"UserID":15,
"Name":"John",
"DisplayName":"John",
"Surname":"Smith",
"Email":"email",
"Telephone":null,
"FullAccount":"true"
}
사용자가 전화 번호를 입력하지 않으면 전화 번호가 null로 표시됩니다.
이 값을 에 할당하는 경우NSString
,에서NSLog
로서 밝혀지고 있다<null>
다음과 같이 문자열을 할당합니다.
NSString *tel = [jsonDictionary valueForKey:@"Telephone"];
이것을 확인하는 올바른 방법은 무엇입니까?<null>
가치요? 저로 인해 저장되지 않는NSDictionary
.
나는 그 조건을 사용해 보았다.[myString length]
그리고.myString == nil
그리고.myString == NULL
또한 iOS 문서에서 이 내용을 가장 잘 읽을 수 있는 위치는 어디입니까?
<null>
NS Null 싱글톤의 로그 방법입니다.그래서:
if (tel == (id)[NSNull null]) {
// tel is null
}
(싱글톤은 추가할 수 없기 때문에 존재합니다.nil
수집 클래스)를 참조해 주세요.
다음은 출연자의 예시입니다.
if (tel == (NSString *)[NSNull null])
{
// do logic here
}
이 Incoming String도 다음과 같이 체크할 수 있습니다.
if(tel==(id) [NSNull null] || [tel length]==0 || [tel isEqualToString:@""])
{
NSlog(@"Print check log");
}
else
{
NSlog(@Printcheck log %@",tel);
}
"불안정" API를 사용하는 경우 null을 확인하기 위해 모든 키를 반복해야 할 수 있습니다.이 문제에 대처하기 위해 카테고리를 작성했습니다.
@interface NSDictionary (Safe)
-(NSDictionary *)removeNullValues;
@end
@implementation NSDictionary (Safe)
-(NSDictionary *)removeNullValues
{
NSMutableDictionary *mutDictionary = [self mutableCopy];
NSMutableArray *keysToDelete = [NSMutableArray array];
[mutDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if (obj == [NSNull null])
{
[keysToDelete addObject:key];
}
}];
[mutDictinary removeObjectsForKeys:keysToDelete];
return [mutDictinary copy];
}
@end
가장 좋은 답변은 Aaron Hayman이 인정받은 답변 아래에 코멘트한 것입니다.
if ([tel isKindOfClass:[NSNull class]])
경고는 표시되지 않습니다. : )
json에 많은 속성이 있는 경우,if
일일이 확인하는 것은 귀찮다.더 나쁜 것은 그 코드가 추악하고 유지하기가 힘들다는 것이다.
보다 나은 접근법은 다음과 같은 카테고리를 만드는 것이라고 생각합니다.NSDictionary
:
// NSDictionary+AwesomeDictionary.h
#import <Foundation/Foundation.h>
@interface NSDictionary (AwesomeDictionary)
- (id)validatedValueForKey:(NSString *)key;
@end
// NSDictionary+AwesomeDictionary.m
#import "NSDictionary+AwesomeDictionary.h"
@implementation NSDictionary (AwesomeDictionary)
- (id)validatedValueForKey:(NSString *)key {
id value = [self valueForKey:key];
if (value == [NSNull null]) {
value = nil;
}
return value;
}
@end
이 카테고리를 Import 한 후 다음 작업을 수행할 수 있습니다.
[json validatedValueForKey:key];
저는 보통 이렇게 해요.
사용자용 데이터 모델이 있고 JSON dict에서 가져온 이메일이라는 NSString 속성이 있다고 가정합니다.응용 프로그램 내에서 전자 메일필드를 사용하는 경우 빈 문자열로 변환하여 크래시를 방지합니다.
- (id)initWithJSONDictionary:(NSDictionary *)dictionary{
//Initializer, other properties etc...
id usersmail = [[dictionary objectForKey:@"email"] copy];
_email = ( usersmail && usersmail != (id)[NSNull null] )? [usersmail copy] : [[NSString alloc]initWithString:@""];
}
Swift에서는 다음 작업을 수행할 수 있습니다.
let value: AnyObject? = xyz.objectForKey("xyz")
if value as NSObject == NSNull() {
// value is null
}
베스트 프랙티스를 고수하는 것이 가장 좋습니다.즉, 실제 데이터 모델을 사용하여 JSON 데이터를 읽는 것입니다.
JSONModel을 보십시오. 사용이 간편하며 [NSNUl null]을 자동으로 *null * 값으로 변환하여 Obj-c에서 다음과 같이 평소처럼 체크를 수행할 수 있습니다.
if (mymodel.Telephone==nil) {
//telephone number was not provided, do something here
}
JSONModel의 페이지를 봐주세요.http://www.jsonmodel.com
JSON 기반 앱을 만들기 위한 간단한 실사 http://www.touch-code-magazine.com/how-to-make-a-youtube-app-using-mgbox-and-jsonmodel/도 소개합니다.http://www.touch-code-magazine.com/how-to-make-a-youtube-app-using-mgbox-and-jsonmodel/
많은 방법을 시도했지만 효과가 없었다.드디어 이게 먹혔어
NSString *usernameValue = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"usernameKey"]];
if ([usernameValue isEqual:@"(null)"])
{
// str is null
}
if([tel isEqual:[NSNull null]])
{
//do something when value is null
}
이것을 시험해 보세요.
if (tel == (NSString *)[NSNull null] || tel.length==0)
{
// do logic here
}
나는 이것을 사용한다.
#define NULL_TO_NIL(obj) ({ __typeof__ (obj) __obj = (obj); __obj == [NSNull null] ? nil : obj; })
만약 그때와 같은 null 값을 얻을 수 있다면 아래 코드 스니펫으로 확인할 수 있습니다.
if(![[dictTripData objectForKey:@"mob_no"] isKindOfClass:[NSNull class]])
strPsngrMobileNo = [dictTripData objectForKey:@"mobile_number"];
else
strPsngrMobileNo = @"";
여기에서는 문자열의 길이를 확인하는 방법으로도 이 작업을 수행할 수 있습니다.
if(tel.length==0)
{
//do some logic here
}
언급URL : https://stackoverflow.com/questions/4839355/checking-a-null-value-in-objective-c-that-has-been-returned-from-a-json-string
'programing' 카테고리의 다른 글
데이터 변경 시 $watch가 실행되지 않음 (0) | 2023.03.14 |
---|---|
스프링 부트(JPA 포함): @Entity를 다른 패키지로 이동 (0) | 2023.03.14 |
여러 HOC 래퍼를 사용하여 React 컴포넌트를 내보내시겠습니까? (0) | 2023.03.14 |
JSON 키 이름 변경 방법 (0) | 2023.03.14 |
오브젝트가 Python에서 JSON serializable인지 쉽게 확인할 수 있는 방법이 있나요? (0) | 2023.03.14 |