1

I need to convert XML response to JSON and sand to the json To javaScript code.

My XML response:
<cell>
       <Result>True</Result>
       <sguid>02291c402-2220-422b-b199-f92f22e56d2f</sguid>
</cell>

I am using XMLReader supporting file from this site:

XMLReader

I am using this code to convert XML to JSON :

+ (NSString*) XMLToJson:(CXMLDocument *)xmlDocument
{
    NSError *error = nil;

    NSArray *resultNodes = [xmlDocument nodesForXPath:@"//cell" error:&error];

    if(error)
        NSLog(@"%@",error.description);

    CXMLNode *cellNode = [resultNodes objectAtIndex:0];

    NSLog(@"%@",cellNode.XMLString);

    NSError *parseError = nil;
    NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:cellNode.XMLString   error:&parseError];

    NSLog(@"%@", xmlDictionary);

  //{print this.
  //  cell =     {
  //      Result =         {
  //          text = True;
  //      };
  //      sguid =         {
  //          text = "0391c402-1120-460b-b199-f92fffe56d2f";
  //      };
  //  };
  //}




    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:xmlDictionary
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if(error)
        NSLog(@"%@",error.description);

     NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", jsonString);

    return jsonString;
}

I got JSON response like this:

{
  "cell" : {
    "Result" : {
      "text" : "True"
    },
    "sguid" : {
      "text" : "0391c402-1120-460b-b199-f92fffe56d2f"
    }
  }
}

I need JSON response like this:

{
  "cell": {
    "Result": "True",
    "sguid": "02291c402-2220-422b-b199-f92f22e56d2f"
  }
}

Because then I send this json to javascript code I get that exception jquery mobile dont know parser this and throws an exception of syntax error.

I've seen programmers use this solution and is helping them but I still get the same result in this solution.

XML into JSON conversion in iOS

thanks

1
  • all you have to do to check if that node has a child node named "text" and has no child node. Then you can extract the real values and skip the "text" nodes in XMLReader :) Commented Apr 4, 2013 at 12:53

2 Answers 2

3

I just wrote a function for your problem, I tried it on with a couple of XMLs. Let me know if you find any issues

- (NSMutableDictionary *)extractXML:(NSMutableDictionary *)XMLDictionary
{
    for (NSString *key in [XMLDictionary allKeys]) {
        // get the current object for this key
        id object = [XMLDictionary objectForKey:key];

        if ([object isKindOfClass:[NSDictionary class]]) {
            if ([[object allKeys] count] == 1 &&
                [[[object allKeys] objectAtIndex:0] isEqualToString:@"text"] &&
                ![[object objectForKey:@"text"] isKindOfClass:[NSDictionary class]]) {
                // this means the object has the key "text" and has no node
                // or array (for multiple values) attached to it. 
                [XMLDictionary setObject:[object objectForKey:@"text"] forKey:key];
            }
            else {
                // go deeper
                [self extractXML:object];
            }
        }
        else if ([object isKindOfClass:[NSArray class]]) {
            // this is an array of dictionaries, iterate
            for (id inArrayObject in (NSArray *)object) {
                if ([inArrayObject isKindOfClass:[NSDictionary class]]) {
                    // if this is a dictionary, go deeper
                    [self extractXML:inArrayObject];
                }
            }
        }
    }

    return XMLDictionary;
}

And use it like this

NSDictionary *clearXML = [[self extractXML:[yourParsedXMLDictionary mutableCopy]] copy];
Sign up to request clarification or add additional context in comments.

2 Comments

Works very well. Thank you. Now I have only the problem that if there is an empty item is sent like this "clubId": {} And I want is send "clubId":"" Because agin then I send this json to javascript code I get that exception jquery mobile dont know parser this and throws an exception of syntax error. Thank you.
then you should add a check in the function and check if the result is an nsdictionary and it contains 0 keys. if so, replace that object with an empty nsstring. I guess you can add that functionality since a similar check is implemented above. Let me know if you have any problems doing it, I will try to help you (for clarity you might consider adding that functionality with another function)
3

Your problem in using XMLReader. For resolve this problem you can use XMLConverter instead of the XMLReader.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.