json 和 结构体 转换

package main

import (
   "encoding/json"
   "fmt"
)

type User struct {
   Id int `json:"id"`
   Name string `json:"name"`
}

func main() {
   //将字符串解析为结构体的形式
   str := `{"id":1,"name":"yang"}`
   var user User
   //将字符串反解析为结构体
   json.Unmarshal([]byte(str),&user)
   fmt.Println(user)     //{1 yang}
   fmt.Printf("%T,%T\n",str,user)  //string,main.User
   //将结构体解析为字符串
   b,e := json.Marshal(user)
   fmt.Println(string(b),e)   //{"id":1,"name":"yang"} <nil>
   fmt.Printf("%T,%T\n",b,e)   //[]uint8,<nil>


   fmt.Printf("------------------------------\n")


   //将字符串反解析为字典
   var m map[string] interface{}
   json.Unmarshal([]byte(str),&m)
   fmt.Println(m)    //map[id:1 name:yang]
   fmt.Printf("%T,%T\n",str,m)   //string,map[string]interface {}
   //将字典解析为字符串
   b,e = json.Marshal(m)
   fmt.Println(string(b),e)   //{"id":1,"name":"yang"} <nil>
   fmt.Printf("%T,%T\n",b,e)  //[]uint8,<nil>

   fmt.Printf("-----------------------------\n")


   //将字符串反解析为数组
   s := `[1,2,3,4,5]`
   var a []int
   json.Unmarshal([]byte(s),&a)
   fmt.Println(a)       //[1 2 3 4 5]
   fmt.Printf("%T,%T\n",s,a)   //string,[]int
   //将数组解析为字符串
   b,e = json.Marshal(a)
   fmt.Println(string(b),e)  //[1,2,3,4,5] <nil>
   fmt.Printf("%T,%T\n",string(b),e)   //string,<nil>
}

将复杂的结构体解析为字符串

package main

import (
   "encoding/json"
   "fmt"
)

type ExploreCommercialCard struct {
   ModuleTitle string  `json:"moduleTitle"`
   SubTitle    string  `json:"subTitle"`
   Tag         string  `json:"tag"`
   Cards       []*Card `json:"cards"`
}

type Card struct {
   Type          uint8    `json:"type"`
   MainTitle     string   `json:"mainTitle"`
   SubTitle      string   `json:"subTitle"`
   TopCoverURL   string   `json:"topCoverUrl"`
   FullCoverURL  string   `json:"fullCoverUrl"`
   RightCoverURL string   `json:"rightCoverUrl"`
   Intro         string   `json:"intro"`
   Chapters      []string `json:"chapters"`
   BtnTitle      string   `json:"btnTitle"`
   *URL
}

type URL struct {
   TargetType  uint8  `json:"targetType"`
   TargetURL   string `json:"targetUrl"`
   TargetValue string `json:"targetValue"`
}

func main() {
   data := ExploreCommercialCard{
      ModuleTitle: "dafsd",
      SubTitle:    "afdsf",
      Tag: "xxxxx",
      Cards: []*Card{&Card{
         Type:          12,
         MainTitle:     "daf",
         SubTitle:      "fda",
         TopCoverURL:   "sdf",
         FullCoverURL:  "daf",
         RightCoverURL: "daf",
         Intro:         "dsaf",
         Chapters:      []string{"lj"},
         BtnTitle:      "da",
         URL: &URL{
            TargetURL: "dfda",
         },
      },
      },
   }

   fmt.Println(data)

// 解析为json格式是将结构体成员名称写位json的格式,输出
// 注意包含关系和继承关系的写法是不同的
// URL 和 Card 是继承关系 ,可以写在同一阶级上
// ExploreCommercialCard 和 Card 是包含关系,需要写在不同的阶级上
// 注意切片的写法
   str,err := json.Marshal(data)   
   fmt.Printf("%T ,%T\n",data,str)
   fmt.Println(string(str),err)
}

输出:

{dafsd afdsf xxxxx [0xc000078000]}
main.ExploreCommercialCard ,[]uint8
{"moduleTitle":"dafsd","subTitle":"afdsf","tag":"xxxxx","cards":[{"type":12,"mainTitle":"daf","subTitle":"fda","topCoverUrl":"sdf","fullCoverUrl":"daf","rightCoverUrl":"daf","intro":"dsaf","chapters":["lj"],"btnTitle":"da","targetType":0,"targetUrl":"dfda","targetValue":""}]}
 <nil>

test:

package aaa

type ExploreIcon struct {
	Icons []*Icon `json:"icons"`
}

type Icon struct {
	Style    uint8      `json:"style"`
	Contents []*Content `json:"content"`
}

type Content struct {
	CoverURL string `json:"coverUrl"`
	Title    string `json:"title"`
	SubTitle string `json:"subTitle"`
	*URL
}

------------------------------------------------------
package bbb

	resource := &aaa.ExploreIcon{
		Icons:[]*aaa.Icon{
			&aaa.Icon{
				Style:    1,
				Contents: []*aaa.Content{
					&aaa.Content{
						CoverURL: "http://coverurl",
						Title:    "title",
						SubTitle: "subtitle",
						URL:      &aaa.URL{
							TargetType:  3,
							TargetURL:   "http://exploreicon?param=$&&param2=$",
							TargetValue: "1,2",
						},
					},
					&aaa.Content{
						CoverURL: "http://coverurl2",
						Title:    "title2",
						SubTitle: "subtitle2",
						URL:      &aaa.URL{
							TargetType:  2,
							TargetURL:   "http://exporeicon2?param=$&&param2=$",
							TargetValue: "3,4",
						},
					},
				},
			},
		},
	}
---------------------------------------------------
取数据:   resource.Icons[0].Contents[1].URL.TargetURL

Demo:

package main

import (
	"encoding/json"
	"fmt"
	"reflect"
)
import _struct "github.com/golang/protobuf/ptypes/struct"

var goTypes = map[string]reflect.Type{
	"bool":                   reflect.TypeOf(false),
	"byte":                   reflect.TypeOf(byte(0)),
	"int":                    reflect.TypeOf(int(0)),
	"uint":                   reflect.TypeOf(uint(0)),
	"rune":                   reflect.TypeOf(rune(0)),
	"int8":                   reflect.TypeOf(int8(0)),
	"uint8":                  reflect.TypeOf(uint8(0)),
	"int16":                  reflect.TypeOf(int16(0)),
	"uint16":                 reflect.TypeOf(uint16(0)),
	"int32":                  reflect.TypeOf(int32(0)),
	"uint32":                 reflect.TypeOf(uint32(0)),
	"int64":                  reflect.TypeOf(int64(0)),
	"uint64":                 reflect.TypeOf(uint64(0)),
	"float32":                reflect.TypeOf(float32(0)),
	"float64":                reflect.TypeOf(float64(0)),
	"complex64":              reflect.TypeOf(complex64(0)),
	"complex128":             reflect.TypeOf(complex128(0)),
	"string":                 reflect.TypeOf(string("")),
	"[]byte":                 reflect.TypeOf([]byte("")),
	"google.protobuf.Struct": reflect.PtrTo(reflect.TypeOf(_struct.Struct{})),
}


func IsBuiltInType(goType string) (find bool) {
	_, find = goTypes[goType]
	return find
}

type ServiceDefinition struct {
	Version       int64                    `json:"version"`
	TypeConfigs   map[string]*TypeConfig   `json:"type_configs"`
	MethodConfigs map[string]*MethodConfig `json:"method_configs"`
}

type TypeConfig struct {
	FieldConfigs []*FieldConfig `json:"field_configs"`
}

type FieldConfig struct {
	Name string `json:"name"`
	Type string `json:"type"`
	Tag  string `json:"tag"`
}

type MethodConfig struct {
	Path        string             `json:"path"`
	TypeConfigs *MethodTypeConfigs `json:"type_configs"`
}

type MethodTypeConfigs struct {
	ReqType  string `json:"req_type"`
	RespType string `json:"resp_type"`
}

func main() {
	/*data := `{
    "version": 0,
    "type_configs": {
        "SamplePayload": {
            "field_configs": [
                {
                    "name": "Version",
                    "type": "int32",
                    "tag": "protobuf:\"varint,1,opt,name=version,json=version,proto3\" json:\"version,omitempty\""
                },
                {
                    "name": "Data",
                    "type": "[]byte",
                    "tag": "protobuf:\"bytes,2,opt,name=data,json=data,proto3\" json:\"data,omitempty\""
                }
            ]
        },
        "SampleReply": {
            "field_configs": [
                {
                    "name": "Ack",
                    "type": "int64",
                    "tag": "protobuf:\"varint,1,opt,name=ack,json=ack,proto3\" json:\"ack,omitempty\""
                },
                {
                    "name": "Payload",
                    "type": "SamplePayload",
                    "tag": "protobuf:\"bytes,2,opt,name=payload,json=payload,proto3\" json:\"payload,omitempty\""
                }
            ]
        },
        "SampleRequest": {
            "field_configs": [
                {
                    "name": "Syn",
                    "type": "int64",
                    "tag": "protobuf:\"varint,1,opt,name=syn,json=syn,proto3\" json:\"syn,omitempty\""
                },
                {
                    "name": "Payload",
                    "type": "SamplePayload",
                    "tag": "protobuf:\"bytes,2,opt,name=payload,json=payload,proto3\" json:\"payload,omitempty\""
                }
            ]
        }
    },
    "method_configs": {
        "SampleMethod": {
            "path": "/your.package.SampleService/SampleMethod",
            "type_configs": {
                "req_type": "SampleRequest",
                "resp_type": "SampleReply"
            }
        }
    }
}
`*/
	serviceDefinition := ServiceDefinition{
		Version: 0,
		TypeConfigs: map[string]*TypeConfig{
			"Sample": {
				FieldConfigs: []*FieldConfig{{
					Name: "aaa",
					Type: "a01",
					Tag: "001",
				 },
				{
					Name: "bbb",
					Type: "b01",
					Tag: "002",
				},
				},
			},
			"SampleReply":{
				FieldConfigs: []*FieldConfig{
					{
						Name: "ccc",
						Type: "c01",
						Tag: "003",
					},
				},
			},
			"SampleRequst":{
				FieldConfigs: []*FieldConfig{
					{
						Name: "ddd",
						Type: "d01",
						Tag: "004",
					},
				},
			},
		},
		MethodConfigs: map[string]*MethodConfig{
			"SampleMethod":{
				Path: "xxxxxxx",
				TypeConfigs: &MethodTypeConfigs{
					RespType: "abc",
					ReqType: "abcd",
				},
			},
		},
	}

	str,err := json.Marshal(serviceDefinition)
	fmt.Println(string(str))
	fmt.Println(err)
	/*err := json.Unmarshal([]byte(data),serviceDefinition)
	if err != nil {
		fmt.Println("err")
	}
	fmt.Println(serviceDefinition)*/

	fmt.Println("-------------------------")

	for typeName,typeConfig := range serviceDefinition.TypeConfigs {
		fmt.Printf("1: %T, %v, %T, %v\n",typeName,typeName,typeConfig,typeConfig)
		for fieldName,fieldConfig := range typeConfig.FieldConfigs {
			fmt.Printf("2: %T, %v, %T, %v\n",fieldName,fieldName,fieldConfig,fieldConfig)
			fieldType := fieldConfig.Type
			fmt.Printf("3: %T,%v\n",fieldType,fieldType)
			if find := IsBuiltInType(fieldType); find {
				fmt.Printf("4: %T,%v\n",find,find)
			}
		}
	}
	fmt.Println("-------------------------")

	fmt.Println(goTypes)
	
	fmt.Printf("%T,%d\n",goTypes,len(goTypes))
	for key,val := range goTypes {
		fmt.Println(key," ---> ",val)
	}
}

输出:

{"version":0,"type_configs":{"Sample":{"field_configs":[{"name":"aaa","type":"a01","tag":"001"},{"name":"bbb","type":"b01","tag":"002"}]},"SampleReply":{"field_configs":[{"name":"ccc","type":"c01","tag":"003"}]},"SampleRequst":{"field_configs":[{"name":"ddd","type":"d01","tag":"004"}]}},"method_configs":{"SampleMethod":{"path":"xxxxxxx","type_configs":{"req_type":"abcd","resp_type":"abc"}}}}
<nil>
-------------------------
1: string, SampleReply, *main.TypeConfig, &{[0xc000060870]}
2: int, 0, *main.FieldConfig, &{ccc c01 003}
3: string,c01
1: string, SampleRequst, *main.TypeConfig, &{[0xc0000608a0]}
2: int, 0, *main.FieldConfig, &{ddd d01 004}
3: string,d01
1: string, Sample, *main.TypeConfig, &{[0xc000060810 0xc000060840]}
2: int, 0, *main.FieldConfig, &{aaa a01 001}
3: string,a01
2: int, 1, *main.FieldConfig, &{bbb b01 002}
3: string,b01

-------------------------
map[[]byte:[]uint8 bool:bool byte:uint8 complex128:complex128 complex64:complex64 float32:float32 float64:float64 google.protobuf.Struct:*structpb.Struct int:int int16:int16 int32:int32 int64:int64 int8:int8 rune:int32 string:string uint:uint uint16:uint16 uint32:uint32 uint64:uint64 uint8:uint8]


map[string]reflect.Type,     20

uint64  --->  uint64
complex128  --->  complex128
[]byte  --->  []uint8
int8  --->  int8
int16  --->  int16
uint16  --->  uint16
float32  --->  float32
uint  --->  uint
uint32  --->  uint32
int64  --->  int64
float64  --->  float64
complex64  --->  complex64
uint8  --->  uint8
byte  --->  uint8
int  --->  int
rune  --->  int32
int32  --->  int32
string  --->  string
google.protobuf.Struct  --->  *structpb.Struct
bool  --->  bool
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值