本文给出一个使用Json实现TLV数据封装的实现示例

1. 使用Json实现TLV数据封装

package util

import(
	"testing"
	"fmt"
	"encoding/json"
)


type TLV struct{
	Type int
	Content []byte
}

type Student struct{
	Name string
	Age int
}
type Work struct{
	Title string
	Salary int
	Company string
}

func TestJson(t *testing.T){
	stu := Student{
		Name: "ivan1001",
		Age: 20,
	}
	work := Work{
		Title: "manager",
		Salary: 20000,
		Company: "the one",
	}

	stucontent, _  := json.Marshal(&stu)
	workcontent, _ := json.Marshal(&work)

	tlv_stu := TLV{
		Type: 1,
		Content: stucontent,
	}
	tlv_work := TLV{
		Type: 2,
		Content: workcontent,
	}

	content_1, _ := json.Marshal(&tlv_stu)
	content_2, _ := json.Marshal(&tlv_work)

	result_1 := &TLV{}
	result_2 := &TLV{}

	err1 := json.Unmarshal(content_1, result_1)
	err2 := json.Unmarshal(content_2, result_2)
	if err1 != nil || err2 != nil{
		fmt.Printf("unmarshal failure: %s", err1.Error())
		return
	}

	if result_1.Type == 1{
		student_res := &Student{}

		err1 = json.Unmarshal(result_1.Content, student_res)
		if err1 != nil{
			fmt.Printf("unmarshal to student failure: %s", err1.Error())
			return
		}
		fmt.Printf("name: %s age: %d\n", student_res.Name, student_res.Age)
	}else if result_1.Type == 2{
		work_res := &Work{}
		err1 = json.Unmarshal(result_1.Content, work_res)
		if err1 != nil{
			fmt.Printf("unmarshal to work failure: %s", err1.Error())
			return
		}
		fmt.Printf("title: %s salary: %d company: %s\n", work_res.Title, work_res.Salary, work_res.Company)
	}
}



[参看]: