SBJsonWriter Nested NSDictionary

纵然是瞬间 提交于 2019-11-26 21:44:48

问题


I'm trying to serialize an objc object with Json to send it to a server.

That same server sends the following on GET for this object type:

 {
   "TypeProperties":[
      {"Key":"prop 0","Value":"blah 0"},
      {"Key":"prop 1","Value":"blah 1"},
      {"Key":"prop 2","Value":"blah 2"},
      {"Key":"prop 3","Value":"blah 3"}
     ],
   "ImageURls":[
      {"Key":"url 0","Value":"blah 0"},
      {"Key":"url 1","Value":"blah 1"},
      {"Key":"url 2","Value":"blah 2"},
      {"Key":"url 3","Value":"blah 3"}
     ]
}

SBJsonWriter produces the following for the matching object/type that I've created in objc:

{
  "TypeProperties": {
    "key 2": "object 2",
    "key 1": "object 1",
    "key 4": "object 4",
    "key 0": "object 0",
    "key 3": "object 3"
  },
  "ImageUrls": {
    "key 0": "url 0",
    "key 1": "url 1",
    "key 2": "url 2"
  }
}

This is how I'm using SBJsonWriter:

SBJsonWriter *writer = [[SBJsonWriter alloc] init];
writer.humanReadable = YES;
NSString* json = [writer stringWithObject:itemToAdd];

Here's my implementation of proxyForJson in the class being serialized (required by SBJsonWriter):

- (NSDictionary*) proxyForJson
{
      return [NSMutableDictionary dictionaryWithObjectsAndKeys:
                self.typeProperties, @"TypeProperties",
                self.imageUrls, @"ImageUrls",
                nil];
}

The class being serialized contains only the two properties: typeProperties and imageUrls (both are NSMutableDictionary).

Now, the problem: the server (not surprisingly) does not parse the Json produced by SBJsonWriter when I perform a POST. And the question: how do I produce Json that matches that which is provided by the server (assuming that matching Json would be parsed correctly on upload).

Thanks in advance for any help.


回答1:


In JSON, { } represents an object (key/value pairs) and [ ] represents an array. Judging by the sample you provided, here's what your server expects:

Top Object: dictionary with two keys: TypeProperties and ImageUrls.

TypeProperties and ImageUrls: each is an array containing one or more objects with two keys: Key and Value. Each key should have its respective value.

To comply with what your server expects, you need a structure similar to this (note this is just a bare example, written directly here, but should point you in the right direction):

NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:
                        @"prop 0", @"Key",
                        @"blah 0", @"Value",
                        nil];

NSArray *typeProperties = [NSArray arrayWithObjects:
                           object, // Add as many similar objects as you want
                           nil];

NSArray *imageUrls = [NSArray arrayWithObjects:
                      object, // Add as many similar objects as you want
                      nil];

Then, in your proxyForJson method, you can use:

- (NSDictionary*) proxyForJson
{
      return [NSDictionary dictionaryWithObjectsAndKeys:
              typeProperties, @"TypeProperties",
              imageUrls, @"ImageUrls",
              nil];
}



回答2:


Here is a simple code demonstrating how to use SBJsonWriter:

#import <Foundation/Foundation.h>

#import "SBJsonWriter.h"


int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSDictionary* aNestedObject = [NSDictionary dictionaryWithObjectsAndKeys:
                                              @"nestedStringValue", @"aStringInNestedObject",
                                              [NSNumber numberWithInt:1], @"aNumberInNestedObject",
                                         nil];

        NSArray * aJSonArray = [[NSArray alloc] initWithObjects: @"arrayItem1", @"arrayItem2", @"arrayItem3", nil];

        NSDictionary * jsonTestDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                             @"stringValue", @"aString",
                                             [NSNumber numberWithInt:1], @"aNumber",
                                             [NSNumber numberWithFloat:1.2345f], @"aFloat",
                                             [[NSDate date] description], @"aDate",
                                             aNestedObject, @"nestedObject",
                                             aJSonArray, @"aJSonArray",
                                             nil];

        // create JSON output from dictionary

        NSError *error = nil;
        NSString * jsonTest = [[[SBJsonWriter alloc] init] stringWithObject:jsonTestDictionary error:&error];

        if ( ! jsonTest ) {
            NSLog(@"Error: %@", error);
        }else{
            NSLog(@"%@", jsonTest);
        } 
    }
    return 0;
}

outputs

{
    "aDate":"2012-09-12 07:39:00 +0000",
    "aFloat":1.2345000505447388,
    "nestedObject":{
        "aStringInNestedObject":"nestedStringValue",
        "aNumberInNestedObject":1
     },
    "aJSonList":["arrayItem1","arrayItem2","arrayItem3"],
    "aString":"stringValue",
    "aNumber":1
}

Notes:

  1. Using 'error' allowed me to figure out that if you write [NSDate date] instead of [[NSDate date] description] you will get a "JSON serialisation not supported for __NSTaggedDate" error.
  2. notice the float rounding error... 1.2345 became 1.2345000505447388


来源:https://stackoverflow.com/questions/11765037/sbjsonwriter-nested-nsdictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!