xcode iOS 中 XML 到 JSON 的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15811629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 03:07:32  来源:igfitidea点击:

XML into JSON conversion in iOS

iosxcodejsonjquery-mobilexml-parsing

提问by Guy Kahlon

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

我需要将 XML 响应转换为 JSON 并将沙子转换为 json To javaScript 代码。

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 支持文件:

XMLReader

XML阅读器

I am using this code to convert XML to JSON :

我正在使用此代码将 XML 转换为 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:

我得到了这样的 JSON 响应:

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

I need JSON response like this:

我需要这样的 JSON 响应:

{
  "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.

因为然后我将此 json 发送到 javascript 代码,我得到异常 jquery mobile dont know parser this 并引发语法错误异常。

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

iOS 中 XML 到 JSON 的转换

thanks

谢谢

回答by Bartu

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

我刚刚为您的问题编写了一个函数,我用几个 XML 对其进行了尝试。如果您发现任何问题,请告诉我

- (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];

回答by Ruslan Soldatenko

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

您在使用 XMLReader 时遇到的问题。为了解决这个问题,您可以使用XMLConverter而不是 XMLReader。