Home > Blockchain >  Exception 'Invalid type in JSON write
Exception 'Invalid type in JSON write

Time:11-16

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:

 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.

CodePudding user response:

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.

  • Related