使用Swift访问JSON数据

时间:2018-08-09 16:46:25

标签: json swift json-serialization

我从以下调用中获得了JSON数据数组:

guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [Any] else {
print("Not containing JSON")
return
}

当我运行print(json)时,我在输出中得到以下信息:

[{
"CREATED_BY" = "DOMAIN\\USER";
"CREATED_DATE" = "2016-11-28T08:43:59";
STATUS = U;
"WIDGET_NUMBER" = K11;
"UPDATED_BY" = "<null>";
"UPDATED_DATE" = "<null>";
}, {
"CREATED_BY" = "DOMAIN\\USER";
"CREATED_DATE" = "2016-05-09T08:46:23";
STATUS = U;
"WIDGET_NUMBER" = 89704;
"UPDATED_BY" = "<null>";
"UPDATED_DATE" = "<null>";
}]

我正在尝试获取JSON数据数组中的所有WIDGETNUMBER值。 json变量是Any类型,到目前为止,我还无法转换为struct。是否有一种简单的方法来从JSON对象获取元素?

4 个答案:

答案 0 :(得分:2)

您似乎有很多字典

$ cc -v main.c
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.7.0
Thread model: posix
InstalledDir: /Applications/Xcode_8.3/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

"/Applications/Xcode_8.3/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang" -cc1 -triple x86_64-apple-macosx10.12.0 -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -discard-value-names -main-file-name main.c -mrelocation-model pic -pic-level 2 -mthread-model posix -mdisable-fp-elim -masm-verbose -munwind-tables -target-cpu penryn -target-linker-version 278.4 -v -dwarf-column-info -debugger-tuning=lldb -resource-dir /Applications/Xcode_8.3/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/8.1.0 -fdebug-compilation-dir /Users/mike/Projects/RCI/trunk/HD1/ButtonTest -ferror-limit 19 -fmessage-length 80 -stack-protector 1 -fblocks -fobjc-runtime=macosx-10.12.0 -fencode-extended-block-signature -fmax-type-align=16 -fdiagnostics-show-option -fcolor-diagnostics -o /var/folders/xc/jc2d96hx25l9ntd2vgnh124m0000gn/T/main-7206a2.o -x c main.c
clang -cc1 version 8.1.0 (clang-802.0.42) default target x86_64-apple-darwin16.7.0
ignoring nonexistent directory "/usr/local/include"
#include "..." search starts here:
#include <...> search starts here:
/Applications/Xcode_8.3/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/8.1.0/include
/Applications/Xcode_8.3/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
/usr/include
/System/Library/Frameworks (framework directory)
/Library/Frameworks (framework directory)
End of search list.

"/Applications/Xcode_8.3/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld" -demangle -lto_library

/Applications/Xcode_8.3/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/libLTO.dylib -no_deduplicate -dynamic -arch x86_64 -macosx_version_min 10.12.0 -o a.out
/var/folders/xc/jc2d96hx25l9ntd2vgnh124m0000gn/T/main-7206a2.o -lSystem

/Applications/Xcode_8.3/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/8.1.0/lib/darwin/libclang_rt.osx.a

答案 1 :(得分:0)

您的内容是Dictionary的数组,因此您必须将每个元素Dictionary转换为Json

for dic in content {
    do {
        let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
        print(jsonData)
    } catch {
        print(error.localizedDescription)
    }
}

或者您可以直接从字典中读取 WIDGET_NUMBER 的值

for dic in content {
    print(dic["WIDGET_NUMBER"] ?? "Not found")
}

答案 2 :(得分:0)

Joakim的答案是获取小部件编号的必要条件。对于您的结构,请确保添加类似这样的内容作为初始化程序来映射您的对象。

let widgetNumber: Int
let user: String

    init?(json:[String:Any]) {

      guard let widgetNumber = json["WIDGET_NUMBER"] as? Int, 
            let user = json["CREATED_BY"] as? String else { return nil }

    self.widgetNumber = widgetNumber
    self.user = user

    }

答案 3 :(得分:0)

如果只需要一个小部件编号数组,则可以使用reduce函数,该函数迭代该数组中的字典并提取小部件编号:

使用您的数据,将其放在情节提要中:

let json = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as! [[String: Any]]

let widgetNumbers = json?.reduce(into: [String]()){ (accum, dict) in
    guard let widget = dict["WIDGET_NUMBER"] as? String else { return }
    accum.append(widget)
}

widgetNumbers // -> ["K11", "89704"]