【Golang | json】golang解析json数据的4种方法
    		       		warning:
    		            这篇文章距离上次修改已过444天,其中的内容可能已经有所变动。
    		        
        		                
                在Golang中,有四种常见的方法可以解析JSON数据:
- 使用encoding/json标准库的json.Unmarshal函数。
- 使用json.NewDecoder方法。
- 使用json.Decode方法。
- 使用第三方库如easyjson或ffjson以获得更好的性能。
以下是每种方法的示例代码:
- 使用json.Unmarshal:
package main
 
import (
    "encoding/json"
    "fmt"
    "log"
)
 
type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}
 
func main() {
    jsonData := []byte(`{"name": "John", "age": 30}`)
    var person Person
 
    err := json.Unmarshal(jsonData, &person)
    if err != nil {
        log.Fatal(err)
    }
 
    fmt.Printf("Name: %v, Age: %v\n", person.Name, person.Age)
}- 使用json.NewDecoder:
package main
 
import (
    "encoding/json"
    "fmt"
    "log"
    "os"
)
 
type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}
 
func main() {
    decoder := json.NewDecoder(os.Stdin)
    var person Person
 
    err := decoder.Decode(&person)
    if err != nil {
        log.Fatal(err)
    }
 
    fmt.Printf("Name: %v, Age: %v\n", person.Name, person.Age)
}- 使用json.Decode:
package main
 
import (
    "encoding/json"
    "fmt"
    "log"
    "strings"
)
 
type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}
 
func main() {
    jsonData := `{"name": "John", "age": 30}`
    jsonDecoder := json.NewDecoder(strings.NewReader(jsonData))
    var person Person
 
    err := jsonDecoder.Decode(&person)
    if err != nil {
        log.Fatal(err)
    }
 
    fmt.Printf("Name: %v, Age: %v\n", person.Name, person.Age)
}- 使用第三方库如easyjson或ffjson:
// 使用easyjson,首先需要安装easyjson工具
// go get github.com/mailru/easyjson
// 然后使用easyjson生成代码
// easyjson -all Person.go
 
package main
 
import (
    "github.com/mailru/easyjson"
)
 
// 此处Person结构体代码由easyjson工具生成
 
func main() {
    jsonData := `{"name": "John", "age": 30}`
    var person Person
 
    err := easyjson.Unmarshal([]byte(jsonData), &person)
    if err != nil {
        panic(err)
    }
 
    println(person.Name, person.Age)
}以上代码提供了四种不同的方法来解析JSON数据,并在可能的情况下提供了如何使用第三方库的示例。在实际应用中,你可以根据具体需求和性能要求选择合适的方法。
评论已关闭