阅读和理解 JSON 字符串表示可能非常乏味。有没有办法以人类可读的方式显示嵌套数组/字典的结构?
最佳答案
我是 stackoverflow 的新手,所以我不知道回答自己的问题是否礼貌。
在过去的几天里,我注意到一些关于识别 JSON 数据结构的问题。
所以我在 Swift 中写了一个小类 JSONStructure
来显示层次结构,只用 prinln()
和 tab
字符作为缩进Xcode 的调试控制台。
例如 Apple 推送通知负载之一——这里是 JSON 表示——...
{
"aps" : {
"alert” : {
“body” : "Acme message received from Johnny Appleseed”,
“action-loc-key” : “VIEW”,
"actions" : [
{
“id" : “delete",
"title" : "Delete"
},
{
“id" : “reply-to”,
"loc-key" : “REPLYTO”,
"loc-args" : [“Jane"]
}
]
},
"badge" : 3,
"sound" : “chime.aiff"
},
"acme-account" : "jane.appleseed@apple.com",
"acme-message" : "message123456"
}
...会这样显示
root node is Dictionary with 3 keys 'aps, acme-message, acme-account'
node 'aps' is Dictionary with 3 keys 'sound, alert, badge'
node 'alert' is Dictionary with 3 keys 'action-loc-key, actions, body'
node 'actions' is Array with 2 items
node [0] is Dictionary with 2 keys 'id, title'
node [1] is Dictionary with 3 keys 'id, loc-args, loc-key'
node 'loc-args' is Array with 1 items
JSONStructure 是一个静态类,不需要使用初始化器
基本功能有3个
JSONStructure.fromFileAtURL("http://domain.com/file.json")
从文件或 URL 中读取 JSON
JSONStructure.fromString("{\"key\":\"value\"}")
从纯字符串读取 JSON
JSONStructure.fromData(data : NSData)
是从NSData对象中读取JSON的指定函数
JSONStructure
使用了NSURLConnection
和NSJSONSerialization
的同步方法sendSynchronousRequest
。不需要第三方类。
class JSONStructure {
static var indent = ""
// check JSON from URL or file path,
// can be http://domain.com/file.json or /Library/Folder/file.json
class func fromFileAtURL(urlOrPath : String)
{
var response: NSURLResponse?
var error : NSError?
let isHttpURL = urlOrPath.hasPrefix("http")
if let url = isHttpURL ? NSURL(string : urlOrPath) : NSURL(fileURLWithPath : urlOrPath) {
let data : NSData?
let request = NSURLRequest(URL: url)
if let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error) {
if let httpResponse = response as? NSHTTPURLResponse {
println("Response statusCode: \(httpResponse.statusCode)")
}
JSONStructure.fromData(data)
} else if error != nil {
println("URLConnection error: \(error!)")
}
} else {
println("Bad URL")
}
}
// check JSON from plain string
class func fromString(string : String)
{
if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
JSONStructure.fromData(data)
} else {
println("could not create NSData object from string")
}
}
// check JSON from NSData object
class func fromData(data : NSData)
{
indent = ""
var jsonError : NSError?
let jsonObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(), error: &jsonError)
if jsonError != nil {
println("JSONSerialization error: \(jsonError!)")
} else {
if let jsonArray = jsonObject as? Array<AnyObject> {
println("root node is Array with \(jsonArray.count) items")
processSubArray(jsonArray)
} else if let jsonDictionary = jsonObject as? Dictionary<String,AnyObject> {
let formattedKeys = join(", ", jsonDictionary.keys.array)
println("root node is Dictionary with \(jsonDictionary.count) keys '\(formattedKeys)'")
processSubDictionary(jsonDictionary)
}
}
}
// recursive function to process an Array node in the JSON structure
private class func processSubArray(jsonArray : Array<AnyObject>)
{
indent += "\t"
for (index, subNode) in enumerate(jsonArray) {
if let subArray = subNode as? Array<AnyObject> {
println("\(indent) node [\(index)] is Array with \(subArray.count) items")
processSubArray(subArray)
} else if let subDictionary = subNode as? Dictionary<String,AnyObject>{
let formattedKeys = join(", ", subDictionary.keys.array)
println("\(indent) node [\(index)] is Dictionary with \(subDictionary.count) keys '\(formattedKeys)'")
processSubDictionary(subDictionary)
}
}
indent = indent.substringToIndex(indent.endIndex.predecessor())
}
// recursive function to process a Dictionary node in the JSON structure
private class func processSubDictionary(jsonDictionary : Dictionary<String,AnyObject>)
{
indent += "\t"
for (key, value) in jsonDictionary {
if let subArray = value as? Array<AnyObject> {
println("\(indent) node '\(key)' is Array with \(subArray.count) items")
processSubArray(subArray)
} else if let subDictionary = value as? Dictionary<String,AnyObject>{
let formattedKeys = join(", ", subDictionary.keys.array)
println("\(indent) node '\(key)' is Dictionary with \(subDictionary.count) keys '\(formattedKeys)'")
processSubDictionary(subDictionary)
}
}
indent = indent.substringToIndex(indent.endIndex.predecessor())
}
}
关于objective-c - 如何在 Swift 或 Objective-C 中获取 JSON 数据结构的人类可读映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31211404/