---
title: "通用编解码-对象创建"
url: "https://goframe.org/docs/components/encoding-gjson-creation"
markdown_url: "https://goframe.org/docs/components/encoding-gjson-creation.md"
locale: "zh-Hans"
version: "2.10.x(Latest)"
section: "组件列表"
category: "组件列表 / 编码解码 / 通用编解码-gjson"
published: "2024-10-21"
updated: "2024-11-13"
description: "使用GoFrame框架的gjson模块创建Json对象。支持多种数据格式如JSON、XML等，并提供了New和Load*方法供使用者调用。详细展示了通过JSON、XML和结构体对象创建Json对象的方法，并提供了示例代码帮助开发者理解和应用。"
keywords: ["GoFrame", "GoFrame框架", "gjson", "对象创建", "JSON", "XML", "数据格式", "结构体对象", "Go开发", "数据解析"]
---

# 通用编解码-对象创建

`gjson` 模块除了最基础支持的 `JSON` 数据格式创建 `Json` 对象，还支持常用的数据格式内容创建 `Json` 对象。支持的数据格式为： `JSON`, `XML`, `INI`, `YAML`, `TOML`, `PROPERTIES`。此外，也支持直接通过 `struct` 对象创建 `Json` 对象。

对象创建常用 `New` 和 `Load*` 方法，更多的方法请查看接口文档： [https://pkg.go.dev/github.com/gogf/gf/v2/encoding/gjson](https://pkg.go.dev/github.com/gogf/gf/v2/encoding/gjson)

### 使用 `New` 方法创建

#### 通过 `JSON` 数据创建

```go
jsonContent := `{"name":"john", "score":"100"}`
j := gjson.New(jsonContent)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
// Output:
// john
// 100
```

#### 通过 `XML` 数据创建

```go
jsonContent := `<?xml version="1.0" encoding="UTF-8"?><doc><name>john</name><score>100</score></doc>`
j := gjson.New(jsonContent)
// Note that there's root node in the XML content.
fmt.Println(j.Get("doc.name"))
fmt.Println(j.Get("doc.score"))
// Output:
// john
// 100
```

#### 通过 `Strcut` 对象创建

```go
type Me struct {
    Name  string `json:"name"`
    Score int    `json:"score"`
}
me := Me{
    Name:  "john",
    Score: 100,
}
j := gjson.New(me)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
// Output:
// john
// 100
```

#### 自定义 `Struct` 转换标签

```go
type Me struct {
    Name  string `tag:"name"`
    Score int    `tag:"score"`
    Title string
}
me := Me{
    Name:  "john",
    Score: 100,
    Title: "engineer",
}
// The parameter <tags> specifies custom priority tags for struct conversion to map,
// multiple tags joined with char ','.
j := gjson.NewWithTag(me, "tag")
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
fmt.Println(j.Get("Title"))
// Output:
// john
// 100
// engineer
```

### 使用 `Load*` 方法创建

最常用的是 `Load` 和 `LoadContent` 方法，前者通过文件路径读取，后者通过给定内容创建 `Json` 对象。方法内部会自动识别数据格式，并自动解析转换为 `Json` 对象。

#### 通过 `Load` 方法创建

1. `JSON` 文件

```go
    jsonFilePath := gtest.DataPath("json", "data1.json")
    j, _ := gjson.Load(jsonFilePath)
    fmt.Println(j.Get("name"))
    fmt.Println(j.Get("score"))
```

2. `XML` 文件

```go
    jsonFilePath := gtest.DataPath("xml", "data1.xml")
    j, _ := gjson.Load(jsonFilePath)
    fmt.Println(j.Get("doc.name"))
    fmt.Println(j.Get("doc.score"))
```

#### 通过 `LoadContent` 创建

```go
jsonContent := `{"name":"john", "score":"100"}`
j, _ := gjson.LoadContent(jsonContent)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
// Output:
// john
// 100
```
