Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Exception 'Invalid type in JSON write

I have an interface that looks like this: #import <Foundation/Foundation.h>

#import <AVFoundation/AVFoundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface AVBase : NSObject

@property NSString *portName;

@property NSString *uid;

@property NSString* port;

- (id) initWithPortName:(NSString *)portName andUID:(NSString *)uid andPort:(AVAudioSessionPort)port;
@end

NS_ASSUME_NONNULL_END

and the .m file

@implementation AVBase
- (id)initWithPortName:(NSString *)portName andUID:(NSString *)uid andPort:(AVAudioSessionPort)port
{
  self = [super init];
  if (self)
  {
    self.portName = portName;
    self.uid = uid;
    self.port = [port description];
  }
  return self;
}
@end

I want to create an array of current outputs for the AVAudioSession, so I do it like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 NSMutableArray *myArray = [[NSMutableArray alloc] init];
  AVAudioSession *session = AVAudioSession.sharedInstance;
  NSArray *outputs = [[session currentRoute] outputs];
  for(AVAudioSessionPortDescription* output in outputs)
  {
    AVBase* av = [AVBase alloc];
    av = [av initWithPortNumber:output.portName andUID:output.UID andPort:output.portType];
    [myArray addObject:av];
  }
  NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:&error];

But when I try to serialize myArray I get an error that says:

Exception 'Invalid type in JSON write (AVBase)

I don’t understand what’s wrong, all the properties in my class are of type NSString so it should work.

>Solution :

NSJSONSerialization accepts only NSArray, NSDictionary, NSString, NSNumber (and NSNull), for its top level, but all sublevels/subproperties too.

myArray is a NSArray of AVBase, and AVBase isn’t one of them.
You need to convert an AVBase into a NSDictionary first.

-(NSDictionary *)toDict {
    return @{@"portName": portName, @"uid": uid, @"port": port};
}

Then:

[myArray addObject:[av toDict]];

If you don’t use AVBase, or just for it, you can construct the NSDictionary directly from AVAudioSessionPortDescription *output, no need to use the AVBase here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading