从Swift

时间:2017-12-16 01:07:56

标签: json swift parsing

我试图阅读JSON文件,但在尝试阅读" ParsedText"时,我一直收到错误。
首先我将序列化的JSON数据转换为类型为[String: Any]的字典,然后我尝试读取dictionary["ParsedResults"]值并将其转换为类型[String: Any]的字典,但它总是失败。

这是JSON文件:

{
    ErrorDetails = "<null>";
    ErrorMessage = "<null>";
    IsErroredOnProcessing = 0;
    OCRExitCode = 1;
    ParsedResults = ( {
            ErrorDetails = "";
            ErrorMessage = "";
            FileParseExitCode = 1;
            ParsedText = "Sample text";
            TextOverlay = {
                HasOverlay = 0;
                Lines = ( );
                Message = "Text overlay is not provided as it is not requested";
            };
        } );
    ProcessingTimeInMilliseconds = 869;
    SearchablePDFURL = "Searchable PDF not generated as it was not requested.";
}

这是swift函数的一部分:

do {
    //create json object from data
    let dictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String: Any]

    for (key, value) in dictionary {
        print("KEY: \(key)")
        print("VALUE: \(value)")
    }

    let parsedResults = dictionary["ParsedResults"] as! [String: Any]
    print("parsedResults: \(parsedResults)")

   } catch let error {
      print("ERROR: Could not serialize jSON Data: \(error.localizedDescription)")
    }
   }

1 个答案:

答案 0 :(得分:0)

如前所述,您所说的 JSON文件不是JSON格式。

它似乎采用经典的基于文本的plist格式。如果您确实想要按原样阅读文件,可以使用import Foundation let data = """ { ErrorDetails = "<null>"; ErrorMessage = "<null>"; IsErroredOnProcessing = 0; OCRExitCode = 1; ParsedResults = ( { ErrorDetails = ""; ErrorMessage = ""; FileParseExitCode = 1; ParsedText = "Sample text"; TextOverlay = { HasOverlay = 0; Lines = ( ); Message = "Text overlay is not provided as it is not requested"; }; } ); ProcessingTimeInMilliseconds = 869; SearchablePDFURL = "Searchable PDF not generated as it was not requested."; } """.data(using: .utf8) do { //create property list object from data let dictionary = try PropertyListSerialization.propertyList(from: data!, options: [], format: nil) as! [String: Any] for (key, value) in dictionary { print("KEY: \(key)") print("VALUE: \(value)") } let parsedResults = dictionary["ParsedResults"] as! [[String: Any]] //<- See Larme's comment. print("parsedResults: \(parsedResults)") } catch let error { print("ERROR: Could not deserialize plist Data: \(error.localizedDescription)") }

<form ...>
  <input type="file"/>
</form>
<div id="myDivWhereUserWillDropTheFile">
</div>

但我建议您检查生成此类文件的部分,并修复它以生成有效的JSON文件。