【问题标题】:XML into JSON conversion in iOSiOS 中 XML 到 JSON 的转换
【发布时间】:2025-12-02 20:20:03
【问题描述】:

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

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

我正在使用来自该站点的 XMLReader 支持文件:

XMLReader

我正在使用此代码将 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;
}

我收到这样的 JSON 响应:

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

我需要这样的 JSON 响应:

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

因为然后我将此 json 发送到 javascript 代码,所以我得到了异常 jquery mobile 不知道解析器并抛出语法错误异常。

我看到程序员使用这个解决方案并正在帮助他们,但我仍然在这个解决方案中得到相同的结果。

XML into JSON conversion in iOS

谢谢

【问题讨论】:

  • 您需要做的就是检查该节点是否有一个名为“text”的子节点并且没有子节点。然后,您可以提取实际值并跳过 XMLReader 中的“文本”节点 :)

标签: ios xcode json jquery-mobile xml-parsing


【解决方案1】:

我刚刚为您的问题编写了一个函数,我用几个 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;
}

并像这样使用它

NSDictionary *clearXML = [[self extractXML:[yourParsedXMLDictionary mutableCopy]] copy];

【讨论】:

  • 效果很好。谢谢你。现在我只有一个问题,如果有一个空项目像这样发送“clubId”:{}我想要发送“clubId”:“”因为agin然后我将这个json发送到javascript代码我得到那个异常jquery mobile不知道解析器并抛出语法错误异常。谢谢。
  • 那么你应该在函数中添加一个检查并检查结果是否是一个 nsdictionary 并且它包含 0 个键。如果是这样,则将该对象替换为空的 nsstring。我想您可以添加该功能,因为上面实现了类似的检查。如果您有任何问题,请告诉我,我会尽力帮助您(为清楚起见,您可能会考虑使用其他功能添加该功能)
【解决方案2】:

您在使用 XMLReader 时遇到的问题。要解决此问题,您可以使用XMLConverter 代替 XMLReader。

【讨论】:

    最近更新 更多