title: NSJSONSerialization Fails to Parse Valid JSON - "Garbage at End"
body: <p>My iOS program is receiving JSON data and trying to parse it but always fails for some reason I cannot determine. Multiple threads are calling this function almost at the same time. This only started happening once I switched to using GCDAsyncSocket, strangely. Here is the relevant code for receiving and parsing data:</p>
  
  <pre><code>// Called whenever I want my program to receive null-terminated data from the server:
  [socket readDataToData:[NSData dataWithBytes:"\0" length:1] withTimeout:10 tag:0];
  
  - (void)socket:(GCDAsyncSocket *)sender didReadData:(NSData *)data withTag:(long)tag{ // a GCDAsyncSocket delegate method
      [self didReceiveNetworkData:data];
  }
  
  - (void)didReceiveNetworkData: (NSData*) data{
      if (TESTING) NSLog(@"Received network data of length %lu===\n%@\n===", (unsigned long) data.length, [[NSString alloc] initWithData: data encoding:NSUTF8StringEncoding]);
      NSError* error;
      NSDictionary* json = [NSJSONSerialization
                            JSONObjectWithData: data
                            options:kNilOptions
                            error:&amp;error];
      if (!json){
          NSLog(@"Got an error parsing received JSON data: %@", error);
          return;
      }
      // Then I handle the dictionary (omitted code)…
  }
  </code></pre>
  
  <p>The log and breakpoint debugger say that this is the data received:</p>
  
  <pre><code>{
  "responseType": -1
  }
  </code></pre>
  
  <p>To be exact, its bytes are "{\n\t\"responseType\":\t-1\n}\0". And I get this "garbage at end" error once the JSONObjectWithData function runs:</p>
  
  <pre><code>Got an error parsing received JSON data: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo=0x10b203800 {NSDebugDescription=Garbage at end.}
  </code></pre>
  
  <p>According to online JSON testers and my own simple test in a separate project, this is valid JSON. So why am I getting an error? I thought that maybe it was complaining about extra bytes after the null terminator, so I tried trimming it by making an NSString out of it then turning that back into NSData, but that did not help:</p>
  
  <pre><code>NSDictionary* json = [NSJSONSerialization
                        JSONObjectWithData: [[[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding] dataUsingEncoding: NSUTF8StringEncoding]
                        options:kNilOptions
                        error:&amp;error];
  </code></pre>
  
  <p>Because using GCDAsyncSocket is what started this problem, I'm wondering if it has to do with multithreading, but I really cannot think of any reason why that would matter. Any ideas?</p>
  
  <p>P.S. I'm using GCDAsyncSocket because I don't know how to deal with low-level sockets in Objective-C, so my original code had tons of weird bugs. </p>