github.com/gogf/gf@v1.16.9/encoding/gjson/gjson_z_unit_struct_test.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package gjson_test
     8  
     9  import (
    10  	"github.com/gogf/gf/encoding/gjson"
    11  	"github.com/gogf/gf/test/gtest"
    12  	"testing"
    13  )
    14  
    15  func Test_GetScan(t *testing.T) {
    16  	type User struct {
    17  		Name  string
    18  		Score float64
    19  	}
    20  	j := gjson.New(`[{"name":"john", "score":"100"},{"name":"smith", "score":"60"}]`)
    21  	gtest.C(t, func(t *gtest.T) {
    22  		var user *User
    23  		err := j.GetScan("1", &user)
    24  		t.Assert(err, nil)
    25  		t.Assert(user, &User{
    26  			Name:  "smith",
    27  			Score: 60,
    28  		})
    29  	})
    30  	gtest.C(t, func(t *gtest.T) {
    31  		var users []User
    32  		err := j.GetScan(".", &users)
    33  		t.Assert(err, nil)
    34  		t.Assert(users, []User{
    35  			{
    36  				Name:  "john",
    37  				Score: 100,
    38  			},
    39  			{
    40  				Name:  "smith",
    41  				Score: 60,
    42  			},
    43  		})
    44  	})
    45  }
    46  
    47  func Test_GetScanDeep(t *testing.T) {
    48  	type User struct {
    49  		Name  string
    50  		Score float64
    51  	}
    52  	j := gjson.New(`[{"name":"john", "score":"100"},{"name":"smith", "score":"60"}]`)
    53  	gtest.C(t, func(t *gtest.T) {
    54  		var user *User
    55  		err := j.GetScanDeep("1", &user)
    56  		t.Assert(err, nil)
    57  		t.Assert(user, &User{
    58  			Name:  "smith",
    59  			Score: 60,
    60  		})
    61  	})
    62  	gtest.C(t, func(t *gtest.T) {
    63  		var users []User
    64  		err := j.GetScanDeep(".", &users)
    65  		t.Assert(err, nil)
    66  		t.Assert(users, []User{
    67  			{
    68  				Name:  "john",
    69  				Score: 100,
    70  			},
    71  			{
    72  				Name:  "smith",
    73  				Score: 60,
    74  			},
    75  		})
    76  	})
    77  }
    78  
    79  func Test_Scan1(t *testing.T) {
    80  	type User struct {
    81  		Name  string
    82  		Score float64
    83  	}
    84  	j := gjson.New(`[{"name":"john", "score":"100"},{"name":"smith", "score":"60"}]`)
    85  	gtest.C(t, func(t *gtest.T) {
    86  		var users []User
    87  		err := j.Scan(&users)
    88  		t.Assert(err, nil)
    89  		t.Assert(users, []User{
    90  			{
    91  				Name:  "john",
    92  				Score: 100,
    93  			},
    94  			{
    95  				Name:  "smith",
    96  				Score: 60,
    97  			},
    98  		})
    99  	})
   100  }
   101  
   102  func Test_Scan2(t *testing.T) {
   103  	type User struct {
   104  		Name  string
   105  		Score float64
   106  	}
   107  	j := gjson.New(`[{"name":"john", "score":"100"},{"name":"smith", "score":"60"}]`)
   108  	gtest.C(t, func(t *gtest.T) {
   109  		var users []User
   110  		err := j.Scan(&users)
   111  		t.Assert(err, nil)
   112  		t.Assert(users, []User{
   113  			{
   114  				Name:  "john",
   115  				Score: 100,
   116  			},
   117  			{
   118  				Name:  "smith",
   119  				Score: 60,
   120  			},
   121  		})
   122  	})
   123  }
   124  
   125  func Test_Struct1(t *testing.T) {
   126  	gtest.C(t, func(t *gtest.T) {
   127  		type BaseInfoItem struct {
   128  			IdCardNumber        string `db:"id_card_number" json:"idCardNumber" field:"id_card_number"`
   129  			IsHouseholder       bool   `db:"is_householder" json:"isHouseholder" field:"is_householder"`
   130  			HouseholderRelation string `db:"householder_relation" json:"householderRelation" field:"householder_relation"`
   131  			UserName            string `db:"user_name" json:"userName" field:"user_name"`
   132  			UserSex             string `db:"user_sex" json:"userSex" field:"user_sex"`
   133  			UserAge             int    `db:"user_age" json:"userAge" field:"user_age"`
   134  			UserNation          string `db:"user_nation" json:"userNation" field:"user_nation"`
   135  		}
   136  
   137  		type UserCollectionAddReq struct {
   138  			BaseInfo []BaseInfoItem `db:"_" json:"baseInfo" field:"_"`
   139  		}
   140  		jsonContent := `{
   141  	"baseInfo": [{
   142  		"idCardNumber": "520101199412141111",
   143  		"isHouseholder": true,
   144  		"householderRelation": "户主",
   145  		"userName": "李四",
   146  		"userSex": "男",
   147  		"userAge": 32,
   148  		"userNation": "苗族",
   149  		"userPhone": "13084183323",
   150  		"liveAddress": {},
   151  		"occupationInfo": [{
   152  			"occupationType": "经商",
   153  			"occupationBusinessInfo": [{
   154  				"occupationClass": "制造业",
   155  				"businessLicenseNumber": "32020000012300",
   156  				"businessName": "土灶柴火鸡",
   157  				"spouseName": "",
   158  				"spouseIdCardNumber": "",
   159  				"businessLicensePhotoId": 125,
   160  				"businessPlace": "租赁房产",
   161  				"hasGoodsInsurance": true,
   162  				"businessScopeStr": "柴火鸡;烧烤",
   163  				"businessAddress": {},
   164  				"businessPerformAbility": {
   165  					"businessType": "服务业",
   166  					"businessLife": 5,
   167  					"salesRevenue": 8000,
   168  					"familyEquity": 6000
   169  				}
   170  			}],
   171  			"occupationWorkInfo": {
   172  				"occupationClass": "",
   173  				"companyName": "",
   174  				"companyType": "",
   175  				"workYearNum": 0,
   176  				"spouseName": "",
   177  				"spouseIdCardNumber": "",
   178  				"spousePhone": "",
   179  				"spouseEducation": "",
   180  				"spouseCompanyName": "",
   181  				"workLevel": "",
   182  				"workAddress": {},
   183  				"workPerformAbility": {
   184  					"familyAnnualIncome": 0,
   185  					"familyEquity": 0,
   186  					"workCooperationState": "",
   187  					"workMoneyCooperationState": ""
   188  				}
   189  			},
   190  			"occupationAgricultureInfo": []
   191  		}],
   192  		"assetsInfo": [],
   193  		"expenditureInfo": [],
   194  		"incomeInfo": [],
   195  		"liabilityInfo": []
   196  	}]
   197  }`
   198  		data := new(UserCollectionAddReq)
   199  		j, err := gjson.LoadJson(jsonContent)
   200  		t.Assert(err, nil)
   201  		err = j.Struct(data)
   202  		t.Assert(err, nil)
   203  	})
   204  }
   205  
   206  func Test_Struct(t *testing.T) {
   207  	gtest.C(t, func(t *gtest.T) {
   208  		type Item struct {
   209  			Title string `json:"title"`
   210  			Key   string `json:"key"`
   211  		}
   212  
   213  		type M struct {
   214  			Id    string                 `json:"id"`
   215  			Me    map[string]interface{} `json:"me"`
   216  			Txt   string                 `json:"txt"`
   217  			Items []*Item                `json:"items"`
   218  		}
   219  
   220  		txt := `{
   221  		  "id":"88888",
   222  		  "me":{"name":"mikey","day":"20009"},
   223  		  "txt":"hello",
   224  		  "items":null
   225  		 }`
   226  
   227  		j, err := gjson.LoadContent(txt)
   228  		t.Assert(err, nil)
   229  		t.Assert(j.GetString("me.name"), "mikey")
   230  		t.Assert(j.GetString("items"), "")
   231  		t.Assert(j.GetBool("items"), false)
   232  		t.Assert(j.GetArray("items"), nil)
   233  		m := new(M)
   234  		err = j.Struct(m)
   235  		t.Assert(err, nil)
   236  		t.AssertNE(m.Me, nil)
   237  		t.Assert(m.Me["day"], "20009")
   238  		t.Assert(m.Items, nil)
   239  	})
   240  }
   241  
   242  func Test_Struct_Complicated(t *testing.T) {
   243  	type CertInfo struct {
   244  		UserRealName        string `json:"userRealname,omitempty"`
   245  		IdentType           string `json:"identType,omitempty"`
   246  		IdentNo             string `json:"identNo,omitempty"`
   247  		CompanyName         string `json:"companyName,omitempty"`
   248  		Website             string `json:"website,omitempty"`
   249  		RegisterNo          string `json:"registerNo,omitempty"`
   250  		AreaCode            string `json:"areaCode,omitempty"`
   251  		Address             string `json:"address,omitempty"`
   252  		CommunityCreditCode string `json:"communityCreditCode,omitempty"`
   253  		PhoneNumber         string `json:"phoneNumber,omitempty"`
   254  		AreaName            string `json:"areaName,omitempty"`
   255  		PhoneAreaCode       string `json:"phoneAreaCode,omitempty"`
   256  		OperateRange        string `json:"operateRange,omitempty"`
   257  		Email               string `json:"email,omitempty"`
   258  		LegalPersonName     string `json:"legalPersonName,omitempty"`
   259  		OrgCode             string `json:"orgCode,omitempty"`
   260  		BusinessLicense     string `json:"businessLicense,omitempty"`
   261  		FilePath1           string `json:"filePath1,omitempty"`
   262  		MobileNo            string `json:"mobileNo,omitempty"`
   263  		CardName            string `json:"cardName,omitempty"`
   264  		BankMobileNo        string `json:"bankMobileNo,omitempty"`
   265  		BankCode            string `json:"bankCode,omitempty"`
   266  		BankCard            string `json:"bankCard,omitempty"`
   267  	}
   268  
   269  	type CertList struct {
   270  		StatusCode uint     `json:"statusCode,string"`
   271  		SrcType    uint     `json:"srcType,string"`
   272  		CertID     string   `json:"certId"`
   273  		CardType   string   `json:"cardType,omitempty"`
   274  		CertInfo   CertInfo `json:"certInfo"`
   275  	}
   276  
   277  	type Response struct {
   278  		UserLevel uint       `json:"userLevel,string,omitempty"`
   279  		CertList  []CertList `json:"certList"`
   280  	}
   281  
   282  	gtest.C(t, func(t *gtest.T) {
   283  		jsonContent := `{
   284  "certList":[
   285  {"certId":"2023313","certInfo":"{\"address\":\"xxxxxxx\",\"phoneNumber\":\"15084890\",\"companyName\":\"dddd\",\"communityCreditCode\":\"91110111MBE1G2B\",\"operateRange\":\"fff\",\"registerNo\":\"91110111MA00G2B\",\"legalPersonName\":\"rrr\"}","srcType":"1","statusCode":"2"},
   286  {"certId":"2023314","certInfo":"{\"identNo\":\"342224196507051\",\"userRealname\":\"xxxx\",\"identType\":\"01\"}","srcType":"8","statusCode":"0"},
   287  {"certId":"2023322","certInfo":"{\"businessLicense\":\"91110111MA00BE1G\",\"companyName\":\"sssss\",\"communityCreditCode\":\"91110111MA00BE1\"}","srcType":"2","statusCode":"0"}
   288  ]
   289  }`
   290  		j, err := gjson.LoadContent(jsonContent)
   291  		t.Assert(err, nil)
   292  		var response = new(Response)
   293  		err = j.Struct(response)
   294  		t.Assert(err, nil)
   295  		t.Assert(len(response.CertList), 3)
   296  		t.Assert(response.CertList[0].CertID, 2023313)
   297  		t.Assert(response.CertList[1].CertID, 2023314)
   298  		t.Assert(response.CertList[2].CertID, 2023322)
   299  		t.Assert(response.CertList[0].CertInfo.PhoneNumber, "15084890")
   300  		t.Assert(response.CertList[1].CertInfo.IdentNo, "342224196507051")
   301  		t.Assert(response.CertList[2].CertInfo.BusinessLicense, "91110111MA00BE1G")
   302  	})
   303  }