1

I am getting a JSON response from the server. I am converting that response using the following Code:

NSString *respone = [[NSString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(@"%@",respone);    //null

NSString *string = [[NSString alloc] initWithData: receivedData encoding:NSASCIIStringEncoding];
NSLog(@"%@",string);  //getting The String

NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:receivedData
                                                                 options:kNilOptions
                                                                   error:&error];

NSLog(@"%@",jsonArray ); //null (I have to use this Array not the string )

Now my problem is for small JSON response it is working fine but in some Case i got a a response (receivedData) over 5080 bytes in that case my response and jsonArray both are coming null. Please Help

My Response Json is:

{"inventorylist":[{"listeddate":"06/06/2015","unitsavailable":1,"photos":[{"image":""},{"image":""}],"availablefortrade":true,"categoryid":266,"inventoryname":"Godzilla (DVD, 1998, Closed Caption)","description":"This is the listing for Godzilla (1998) on DVD. Disc has never been watched. Comes in the original case with original artwork. Shipping: I will charge $1.05 for a tracking number. The sooner you pay me, the sooner it arrives in your mailbox.","subcategoryname":"DVD Movies","categoryname":"DVD's/ Media","subsubcategoryname":"null","parentcategory":"DVD's/ Media","subcategoryid":266,"inventoryid":86,"subsubcategoryid":"null"},{"listeddate":"06/06/2015","unitsavailable":1,"photos":[{"image":""}],"availablefortrade":true,"categoryid":53,"inventoryname":"Handbook of Medical-Surgical Nursing, Springhouse, Good, Books","description":"payment | shipping rates | returns Handbook of Medical-Surgical Nursing Product Category : Books ISBN : 1582554455 Title : Handbook of Medical-Surgical Nursing EAN : 9781582554457 Authors : Springhouse Binding : Paperback Publisher : Lippincott Williams & Wilkins Publication Date : 2005-07-28 Pages : 1024 Signed : False First Edition : False Dust Jacket : False List Price (MSRP) : 46.95 Height : 1.3000 inches Width : 5.0000 inches Length : 8.0000 inches Weight : 1.5500 pounds Condition : Good Great reading copy, some spine wear. NO INTERNATIONAL SHIPPING About Sandusky Bay Area Goodwill Industries Our company is dedicated to providing you with the best quality, lowest cost products on eBay. Payment We accept PayPal for all eBay orders. Please see payment details below. Shipping Multiple shipping options are available for this item. For more detail, please see below, and select the shipping option that is most convenient for you. International Shipping: Import duties, taxes, and charges are NOT INCLUDED in the item price or shipping charges. These charges are the buyer's responsibility. Please check with your country's customs office to determine what these additional costs will be prior to bidding / buying. These charges are normally collected by the delivering freight (shipping) company or when you pick the item up do not confuse them for additional shipping charges. We do not mark merchandise values below value or mark items as \"gifts.\" US and International government regulations prohibit such behavior. Returns Your satisfaction is very important to us. Please contact us via the methods available within eBay regarding any problems before leaving negative feedback. Any defects, damages, or material differences with your item, must be reported to us within 7 days of receipt of the item or 30 days from date of shipment. The returned merchandise must be postmarked within 30 days of the shipment notification. Non-deliveries must be reported within 30 days of Shipment Notification. Undeliverable, unclaimed, refused, or insufficient addresses will be subject to a 20% restocking fee plus the cost of shipping. � 2015 Sandusky Bay Area Goodwill Industries","subcategoryname":"TextBooks","categoryname":"Books","subsubcategoryname":"null","parentcategory":"Books","subcategoryid":53,"inventoryid":87,"subsubcategoryid":"null"},{"listeddate":"06/06/2015","unitsavailable":1,"photos":[{"image":""}],"availablefortrade":true,"categoryid":266,"inventoryname":"The West Wing - The Complete First Season (DVD, 2003, 4-Disc Set)","description":"This auction is for 1 dvd box set movie: DVD listed above. DVD are used, but it does work fine�.no problems or damage/comes in original box, UNLESS OTHERWISE NOTED. We do combine shipping on multiple items. If the item is listed at $2.99 shipping, it will ship for $1 extra shipping for each additional item. Larger items are combined using the weight for the total price. We accept paypal (preferred). If you have any questions or concerns, please call 256-894-9994 during business hours: 8am-6pm 7 days a week.","subcategoryname":"DVD Movies","categoryname":"DVD's/ Media","subsubcategoryname":"null","parentcategory":"DVD's/ Media","subcategoryid":266,"inventoryid":88,"subsubcategoryid":"null"},{"listeddate":"06/08/2015","unitsavailable":1,"photos":[{"image":""}],"availablefortrade":true,"categoryid":526,"inventoryname":"Brain Age: Train Your Brain in Minutes a Day (Nintendo DS, 2006) GAME ONLY","description":"Up for auction is Nintendo DS Brain Age video game, no case or instructions, just the game. Very nice condition, almost like new. Please ask any and all questions prior to bidding and please don't bid if you don't intend to pay. Thanks for looking!","subcategoryname":"Other","categoryname":"Video Games","subsubcategoryname":"null","parentcategory":"Video Games","subcategoryid":526,"inventoryid":97,"subsubcategoryid":"null"}]}

Shruti
  • 1,849
  • 1
  • 13
  • 21
  • Try to post your error in `JSONObjectWithData ` – Leo Jun 08 '15 at 06:52
  • Please check out - http://stackoverflow.com/questions/7520615/how-to-convert-an-nsdata-into-an-nsstring-hex-string/12442672#12442672 – Santu C Jun 08 '15 at 07:01
  • What happens if you try to `NSLog` the contents of `receivedData`? – mttrb Jun 08 '15 at 07:35
  • @mttrb I added break pint and checked. Received data is proper. I am getting Proper Json in that – Shruti Jun 08 '15 at 07:40
  • I'm surprised you can't convert `receivedData` into either an `NSString` or use `JSONObjectWithData:` – mttrb Jun 08 '15 at 07:47
  • @mttrb : My code is working in mostly all the cases. But all json response are small only. I got one response of 5080 bytes it is not working. I am not getting why it is not working. I checked JSON is proper. – Shruti Jun 08 '15 at 07:49
  • Are you sure your whole receivedData has a valid UTF-8 encoding? Would it be possible to share your 5080 byte receivedData value? – ntsh Jun 08 '15 at 08:23
  • @ntsh When i tried ascii coding it gave me the string. But i want the response a a Array/ Dictionary – Shruti Jun 08 '15 at 08:31
  • I'd like to see the code that creates the NSData. I hope you are not doing something stupid like getting partial responses from the server and converting them to strings directly, or trying to parse partial responses from the server. – gnasher729 Jun 08 '15 at 11:05

2 Answers2

2

It is due to, your receivedData json string contains some spacial character in description key of json:

{
                "listeddate": "06/06/2015",
                "unitsavailable": 1,
                "photos": [
                    {
                        "image": ""
                    }
                ],
                "availablefortrade": true,
                "categoryid": 53,
                "inventoryname": "Handbook of Medical-Surgical Nursing, Springhouse, Good, Books",
                "description": "payment | shipping rates | returns Handbook of Medical-Surgical Nursing Product Category : Books ISBN : 1582554455 Title : Handbook of Medical-Surgical Nursing EAN : 9781582554457 Authors : Springhouse Binding : Paperback Publisher : Lippincott Williams & Wilkins Publication Date : 2005-07-28 Pages : 1024 Signed : False First Edition : False Dust Jacket : False List Price (MSRP) : 46.95 Height : 1.3000 inches Width : 5.0000 inches Length : 8.0000 inches Weight : 1.5500 pounds Condition : Good Great reading copy, some spine wear. NO INTERNATIONAL SHIPPING About Sandusky Bay Area Goodwill Industries Our company is dedicated to providing you with the best quality, lowest cost products on eBay. Payment We accept PayPal for all eBay orders. Please see payment details below. Shipping Multiple shipping options are available for this item. For more detail, please see below, and select the shipping option that is most convenient for you. International Shipping: Import duties, taxes, and charges are NOT INCLUDED in the item price or shipping charges. These charges are the buyer's responsibility. Please check with your country's customs office to determine what these additional costs will be prior to bidding / buying. These charges are normally collected by the delivering freight (shipping) company or when you pick the item up do not confuse them for additional shipping charges. We do not mark merchandise values below value or mark items as \"gifts.\" US and International government regulations prohibit such behavior. Returns Your satisfaction is very important to us. Please contact us via the methods available within eBay regarding any problems before leaving negative feedback. Any defects, damages, or material differences with your item, must be reported to us within 7 days of receipt of the item or 30 days from date of shipment. The returned merchandise must be postmarked within 30 days of the shipment notification. Non-deliveries must be reported within 30 days of Shipment Notification. Undeliverable, unclaimed, refused, or insufficient addresses will be subject to a 20% restocking fee plus the cost of shipping. � 2015 Sandusky Bay Area Goodwill Industries",
                "subcategoryname": "TextBooks",
                "categoryname": "Books",
                "subsubcategoryname": "null",
                "parentcategory": "Books",
                "subcategoryid": 53,
                "inventoryid": 87,
                "subsubcategoryid": "null"
            }

which is not getting encoded properly by NSUTF8StringEncodingand before successful encoding of data it is breaking it and providing you "null" string.

Try doing it in this way:

NSString *string = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
NSData *utf8Data = [string dataUsingEncoding:NSUTF8StringEncoding];

// ... give utf8Data to NSJSONSerializer
Akshay Sunderwani
  • 12,428
  • 8
  • 29
  • 52
  • Thank you so much. It solved my error. Just one question. I can add this code anywhere ? I mean if i am not getting any special character and has `NSUTF8StringEncoding` ony still i can add this? – Shruti Jun 08 '15 at 09:16
  • @Shruti you can add but it is not proper solution of it, it is kind of a patch. It must be properly encountered on web end points so that this does not happen again. Proper solution is to make sure what type of encoding is being used at web end points and you also must use same encoding type. – Akshay Sunderwani Jun 08 '15 at 09:44
  • Actually i asked them. They said we are not using any encoding by themselves. They are using some tool.library to get the json. – Shruti Jun 08 '15 at 09:46
  • @Shruti then to keep on safe end you can add it. But also check case of every special character so that it must not create a problem later on. – Akshay Sunderwani Jun 08 '15 at 09:49
  • 2
    You should always parse the original NSData from the server. If converting it to a string and back helps in any way then the server is sending bad JSON data and the server needs to be fixed. JSON has no problems whatsoever handling any Unicode data. – gnasher729 Jun 08 '15 at 11:01
2

You only ever convert the original NSData that you received from the server using NSJSONSerialization. And you only ever convert the complete NSData, if the server or your code gives you partial responses. Partial responses cannot be parsed. Converting to a string and back doesn't always work with valid JSON. That's why I would want to see the code that produces your NSData; that's most likely where the problem comes from.

If NSJSONSerialization returns nil, then you check the error code. Whatever the error code, if it returns nil, then the fault is in the JSON data that you received. The server is sending you faulty data. You MUST not try to fix the data on the receiving end, this is a problem that needs to be fixed on the server.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • Thank you for the explanation. It is giving me `Unable to convert data to string around character 3647` error. It is a special character. I asked backend people to handle this But I want to fix it on my side also. It there any good solution? – Shruti Jun 08 '15 at 11:21