Swift Protobuf 初探 —— 繼 XML 后,JSON 也要被淘汰了嗎

MerDicks 8年前發布 | 23K 次閱讀 Swift JSON Apple Swift開發 protobuf

Protocol Buffers 是什么?

Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler. —— Google Official Definition

簡單地說,Protocol Buffers 就是一種輕量高效的結構化數據交換格式,語言無關、平臺無關、可擴展。理解地直白粗暴一點就是“更厲害更面向未來的 JSON”,那么接下來我們就將通過 Swift 官方實現的 Protobuf 來一探究竟。

Swift Protobuf

從去掉軟盤到干掉光驅,從擯棄 Flash 推廣 HTML5 ,到現在干脆把標準音頻接口抹去,蘋果一向善于引領科技時尚,那么在面向未來的數據交換格式上自然不會落后,因此 Swift Protobuf 應運而生。

開始動手嘗試吧

本來我想拿照官方示例來走一遍的,但這次正好有個絕佳的示例,既有客戶端又有服務端,可以“做”享其成一次,其中還涉及到 Go 語言,趁此機會也可以把玩一番。

將 ProtoBufExample 克隆至本地

? git clone https://github.com/KyoheiG3/ProtobufExample.git
? cd ProtobufExample

配置客戶端

? cd ./ProtobufClient
? pod install

初始化服務端

? cd ./ProtobufServer
? swift build
// 創建工程文件,以便在 Xcode 下編輯
? swift package generate-xcodeproj

啟動 API

? ./.build/debug/api

配置并啟動服務 with Go

? go get github.com/golang/protobuf/protoc-gen-go
? go run server/api.go

有必要的話,先下載安裝 Go 語言環境,并配置 $GOPATH

? mkdir ~/go
? export GOPATH=~/go
? export PATH=$PATH:$GOPATH/bin

體會 .proto

安裝 protobuf

? brew install protobuf

用 Swift 編譯 protobuf

? cd ./ProtobufServer
? swift build
? protoc --plugin=protoc-gen-swift=.build/debug/protoc-gen-swift --swift_out=../protos --proto_path=../protos ../protos/DataModel.proto

此時我們就能在 protos 這個輸出目錄下就可以看到剛剛生成的對應 .pb.swift 文件了。

/*
 * Generated by the protocol buffer compiler.
 * Source: DataModel.proto
 */
import Foundation
import SwiftProtobuf
public struct BookInfo: ProtobufGeneratedMessage {
  public var swiftClassName: String {return "BookInfo"}
  public var protoMessageName: String {return "BookInfo"}
  public var protoPackageName: String {return ""}
  public var jsonFieldNames: [String: Int] {return [
    "id": 1,
    "title": 3,
    "author": 2,
  ]}
  public var protoFieldNames: [String: Int] {return [
    "id": 1,
    "title": 3,
    "author": 2,
  ]}
  public var id: Int64 = 0
  public var title: String = ""
  public var author: String = ""
  public init() {}
  ......
  ......
  ......
  if !keys.isEmpty {
      try visitor.visitMapField(fieldType: ProtobufMap





 .self, value: keys, protoFieldNumber: 4, protoFieldName: "keys", jsonFieldName: "keys", swiftFieldName: "keys")
    }
  }
  public func _protoc_generated_isEqualTo(other: MyLibrary) -> Bool {
    if id != other.id {return false}
    if name != other.name {return false}
    if books != other.books {return false}
    if keys != other.keys {return false}
    return true
  }
}


  

其中還包括了一些對 JSON 的友好兼容,感興趣的朋友可以自己動手玩一下。

 

 

來自:http://www.cocoachina.com/swift/20161128/18202.html

 

 本文由用戶 MerDicks 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!