4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

NSJsonSerialization JSONパース時の、型調査

Posted at

NSSerialization JSONObjectWithDataでJSONをパースした時に、JSONの型がObjective-cのどの型に対応するか調査してみた。
iOS7でやってます。

こんなJSONを用意して・・・

{
   "IntAsString":"100",
   "IntAsNumber":100,
   "DoubleAsString":"0.03043054930804984029",
   "DoubleAsNumber":0.03043054930804984029,
   "BoolAsString":"false",
   "BoolAsBool":false,
   "NullAsString":"null",
   "NullAsNull":null,
   "String":"String",
   "Array":[
      0,
      0,
      0,
      0
   ],
   "Object":{
      "Hoge":"Fuga",
      "Foo":0
   }
}

こんなコードで型を列挙

 NSString *tJsonTest = @"{\"IntAsString\":\"100\", \"IntAsNumber\":100, \"DoubleAsString\":\"0.03043054930804984029\", \"DoubleAsNumber\":0.03043054930804984029, \"BoolAsString\":\"false\", \"BoolAsBool\": false, \"NullAsString\":\"null\", \"NullAsNull\":null, \"String\": \"String\", \"Array\": [0,0,0,0], \"Object\": {\"Hoge\":\"Fuga\", \"Foo\":0}}";
NSDictionary *tDict = [NSJSONSerialization JSONObjectWithData:[tJsonTest dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];

for(NSString *tKey in tDict.allKeys) {
    NSLog(tKey);
    NSLog(NSStringFromClass([tDict[tKey] class]));
}

するとこんなログが。

2013-10-23 19:13:58.489 TestApp[33436:a0b] NullAsString
2013-10-23 19:13:58.491 TestApp[33436:a0b] __NSCFString
2013-10-23 19:13:58.491 TestApp[33436:a0b] String
2013-10-23 19:13:58.492 TestApp[33436:a0b] __NSCFString
2013-10-23 19:13:58.492 TestApp[33436:a0b] Array
2013-10-23 19:13:58.492 TestApp[33436:a0b] __NSCFArray
2013-10-23 19:13:58.493 TestApp[33436:a0b] IntAsNumber
2013-10-23 19:13:58.494 TestApp[33436:a0b] __NSCFNumber
2013-10-23 19:13:58.494 TestApp[33436:a0b] IntAsString
2013-10-23 19:13:58.495 TestApp[33436:a0b] __NSCFString
2013-10-23 19:13:58.495 TestApp[33436:a0b] BoolAsString
2013-10-23 19:13:58.496 TestApp[33436:a0b] __NSCFString
2013-10-23 19:13:58.496 TestApp[33436:a0b] NullAsNull
2013-10-23 19:13:58.496 TestApp[33436:a0b] NSNull
2013-10-23 19:13:58.497 TestApp[33436:a0b] Object
2013-10-23 19:13:58.497 TestApp[33436:a0b] __NSCFDictionary
2013-10-23 19:13:58.498 TestApp[33436:a0b] DoubleAsString
2013-10-23 19:13:58.498 TestApp[33436:a0b] __NSCFString
2013-10-23 19:13:58.499 TestApp[33436:a0b] DoubleAsNumber
2013-10-23 19:13:58.499 TestApp[33436:a0b] __NSCFNumber
2013-10-23 19:13:58.499 TestApp[33436:a0b] BoolAsBool
2013-10-23 19:13:58.500 TestApp[33436:a0b] __NSCFBoolean
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?