求 JSON根据字段自动排序啊

hellsam · · 2117 次点击
``` type AutoGenerated struct { Priority string `json:"priority"` Remark string `json:"remark"` } type AutoGeneratedList []AutoGenerated //实现了sort接口中的三个方法,则可以使用排序方法了 func (lrl *AutoGeneratedList) Len() int { return len(*lrl) } func (lrl *AutoGeneratedList) Swap(i, j int) { (*lrl)[i], (*lrl)[j] = (*lrl)[j], (*lrl)[i] } func (lrl *AutoGeneratedList) Less(i, j int) bool { return (*lrl)[i].Priority < (*lrl)[j].Priority } func Test_gg(t *testing.T) { var autoGeneratedList AutoGeneratedList jsonByte := `[{"priority":"6","remark":"备注3"},{"priority":"1","remark":"备注2"},{"priority":"2","remark":"备注1"},{"priority":"1","remark":"备注0"}]` if err := json.Unmarshal([]byte(jsonByte), &autoGeneratedList); err != nil { t.Fatal(err) } fmt.Println("sort before : ") for _, value := range autoGeneratedList { fmt.Println(value) } // 自动排序 sort.Sort(&autoGeneratedList) fmt.Println("sort after : ") for _, value := range autoGeneratedList { fmt.Println(value) } } ``` ``` sort before : {6 备注3} {1 备注2} {2 备注1} {1 备注0} sort after : {1 备注2} {1 备注0} {2 备注1} {6 备注3} ```
#1