문자열을 JSON 형식으로 변환하는 일반적인 작업. 네, 쉽고, 이것에 대한 StackOverflow에 대한 많은 답변이 있습니다.JSON 형식 : 올바른 순서로 출력하기
쉽게 이해할 수없는 것은 내가 얻는 순서가 NSDictionary에 쌍 개체를 놓는 순서와 다른 이유입니다.
-(NSString*)createJSONstring
{
//http://www.raywenderlich.com/5492/working-with-json-in-ios-5
NSDictionary* dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
@"<xx3-xxxx>",@"from",
@"<xxx-xxx>",@"to",
@"<Bla bla bla>",@"message",
@"<2000>",@"posixtime", nil];
NSArray* notifications = [NSArray arrayWithObjects:dictionary, nil];
NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:NSJSONWritingPrettyPrinted error:&writeError];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"JSON Output: %@", jsonString);
return jsonString;
}
내가 이런 일을 기대할 것입니다 : 내가 쓴 코드의
{
"from" : "<xx3-xxxx>"
"to" : "<xxx-xxx>",
"message" : "<Bla bla bla>",
"posixtime" : "<2000>",
}
는하지만 다른 순서로 얻을 :
{
"posixtime" : "<2000>", <----- INCORRECT
"to" : "<xxx-xxx>",
"message" : "<Bla bla bla>",
"from" : "<xx3-xxxx>" <----- INCORRECT
}
어떻게을 나는 그것을 배열에 삽입 할 때 동일한 순서로 결과를 얻는다. NSDictionary
에
[NSDictionary dictionaryWithObjectsAndKeys: //I want it to be:
@"<xx3-xxxx>",@"from", //1st
@"<xxx-xxx>",@"to", //2nd
@"<Bla bla bla>",@"message", //3rd
@"<2000>",@"posixtime", nil]; //4th
일반적으로 사전을 사용하면 키를 기준으로 값에 액세스하므로 주문과 관련이 없습니다. 키순 항목을 일관된 순서로 사용해야하는 유스 케이스를 확장 할 수 있습니까? – GnarlyDog
JSON "객체"에서 키/값 쌍의 순서가 유지되지 않을 수도 있습니다. –
json.org : "객체는 정렬되지 않은 * 이름/값 쌍의 집합입니다." –