IOS converts Nsarray, nsdictionary to JSON format for network transfer

Source: Internet
Author: User
Tags vars

http://blog.csdn.net/worldzhy/article/details/49982491

It is often used to convert Nsarray and nsdictionary into JSON format, but iOS does not provide a convenient library of methods. We simulate an example, assuming that we need to convert an array of a custom model (class with only a few attributes) into a JSON string, which is passed to the backend as a parameter to the backend, and the implementation method is given below:

[OBJC]View PlainCopy
  1. Hspicturemodel Array to JSON
  2. -(NSString *) Picturearraytojson: (nsarray *) Picarr {
  3. if (Picarr && picarr. Count > 0) {
  4. Nsmutablearray *arr = [Nsmutablearray arraywithcapacity:0];
  5. For (Hspicturemodel *model in Picarr) {
  6. NSData *jsondata = [Object2Json getjson:model options:nsjsonwritingprettyprinted error: nil];
  7. nsstring *jsontext = [[NSString alloc] initwithdata:jsondata encoding:nsutf8StringEncoding];
  8. [arr Addobject:jsontext];
  9. }
  10. return [self Objarraytojson:arr];
  11. }
  12. return Nil;
  13. }
  14. Above this method <span style="FONT-SIZE:18PX;" > The first step is to convert a model to a JSON string and then stitch together the strings in the array to get the final JSON string. We have achieved our purpose.  The code used for the object2Json is attached to the bottom of the article.
  15. </span>
  16. Convert multiple JSON strings to a JSON string
  17. -(NSString *) Objarraytojson: (nsarray *) array {
  18. nsstring *jsonstr = @ "[";
  19. For (Nsinteger i = 0; i < array. Count; ++i) {
  20. if (i! = 0) {
  21. JSONSTR = [Jsonstr stringbyappendingstring:@ ","];
  22. }
  23. JSONSTR = [Jsonstr stringbyappendingstring:array[i]];
  24. }
  25. JSONSTR = [Jsonstr stringbyappendingstring:@ "]"];
  26. return jsonstr;
  27. }

Above, we realize the data from the client to the background when the conversion may be required, and then look at how to send the background JSON form of the string, the client to understand the Nsarray or nsdictionary.

[OBJC]View PlainCopy
  1. JSON string to array
  2. -(Nsarray *) Stringtojson: (NSString *) jsonstr {
  3. if (jsonstr) {
  4. ID tmp = [nsjsonserialization jsonobjectwithdata:[jsonstr datausingencoding:nsutf8StringEncoding] options:nsjsonreadingallowfragments | nsjsonreadingmutableleaves |  Nsjsonreadingmutablecontainers error: nil];
  5. if (TMP) {
  6. if ([tmp Iskindofclass:[nsarray class]]) {
  7. return tmp;
  8. } Else if ([tmp iskindofclass:[nsstring class]]
  9. || [TMP Iskindofclass:[nsdictionary class]]) {
  10. return [Nsarray arraywithobject:tmp];
  11. } Else {
  12. return Nil;
  13. }
  14. } Else {
  15. return Nil;
  16. }
  17. } Else {
  18. return Nil;
  19. }
  20. }


This standalone approach enables the ability to convert back-end JSON strings to Nsarray or nsdictionary.

Finally, the implementation of the Object2json class is attached, and the implementation is excerpt from the network.

[OBJC]View PlainCopy
    1. #import "Object2Json.h"
    2. #import <objc/runtime.h>
    3. @implementation Object2Json
    4. + (nsdictionary*) GetObjectData: (id) obj
    5. {
    6. nsmutabledictionary *dic = [nsmutabledictionary dictionary];
    7. unsigned int propscount;
    8. objc_property_t *props = class_copypropertylist ([obj class], &propscount);
    9. For (int i = 0;i < Propscount; i++)
    10. {
    11. objc_property_t prop = Props[i];
    12. nsstring *propname = [NSString stringwithutf8string:property_getname (prop)];
    13. id value = [obj valueforkey:propname];
    14. if (value = = nil)
    15. {
    16. Value = [NSNull null];
    17. }
    18. Else
    19. {
    20. Value = [self getobjectinternal:value];
    21. }
    22. [DiC Setobject:value Forkey:propname];
    23. }
    24. return dic;
    25. }
    26. + (nsdata*) Getjson: (ID) obj options: (nsjsonwritingoptions) Options Error: (nserror**) Error
    27. {
    28. return [nsjsonserialization datawithjsonobject:[self getobjectdata:obj] options:options   Error:error];
    29. }
    30. + (ID) getobjectinternal: (id) obj
    31. {
    32. if ([obj iskindofclass:[nsstring class]]
    33. || [Obj Iskindofclass:[nsnumber class]]
    34. || [Obj iskindofclass:[nsnull class]])
    35. {
    36. return obj;
    37. }
    38. if ([obj Iskindofclass:[nsarray class]])
    39. {
    40. nsarray *objarr = obj;
    41. Nsmutablearray *arr = [Nsmutablearray arraywithcapacity:objarr. Count];
    42. For (int i = 0;i < Objarr. Count; i++)
    43. {
    44. [Arr setobject:[self getobjectinternal:[objarr objectatindex:i]] atindexedsubscript:i];
    45. }
    46. return arr;
    47. }
    48. if ([obj iskindofclass:[nsdictionary class]])
    49. {
    50. nsdictionary *objdic = obj;
    51. nsmutabledictionary *dic = [nsmutabledictionary dictionarywithcapacity:[objdic Count]];
    52. For (nsstring *key in Objdic. AllKeys)
    53. {
    54. [DiC setobject:[self getobjectinternal:[objdic Objectforkey:key]] Forkey:key];
    55. }
    56. return dic;
    57. }
    58. return [self getobjectdata:obj];
    59. }
    60. @end

IOS converts Nsarray, nsdictionary to JSON format for network transfer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.