支持从json动态生成结构体,并转化为指定格式 #6
| @ -75,6 +75,7 @@ func (oj *ownJson) Marshal(marshalType string) ([]byte, error) { | |||||||
| // generateStructField 递归解析 | // generateStructField 递归解析 | ||||||
| func (oj *ownJson) generateStructField(rootPath string, currentName string, currentResult gjson.Result) { | func (oj *ownJson) generateStructField(rootPath string, currentName string, currentResult gjson.Result) { | ||||||
| 	structPath := oj.getPath(rootPath, currentName) | 	structPath := oj.getPath(rootPath, currentName) | ||||||
|  | 	fmt.Println(structPath) | ||||||
| 	if currentResult.IsBool() { | 	if currentResult.IsBool() { | ||||||
| 		// bool类型 | 		// bool类型 | ||||||
| 		oj.structBuilder.AddField(structPath, "", true, "", false) | 		oj.structBuilder.AddField(structPath, "", true, "", false) | ||||||
| @ -123,8 +124,8 @@ func (oj *ownJson) generateStructField(rootPath string, currentName string, curr | |||||||
| 			return | 			return | ||||||
| 		} | 		} | ||||||
| 		if arrList[0].IsArray() { | 		if arrList[0].IsArray() { | ||||||
| 			// 数组就不递归处理了, 支持到二维 | 			// 数组递归处理 | ||||||
| 			oj.structBuilder.AddField(structPath, "", [][]any{}, "", false) | 			oj.generateStructField(structPath+".[]", "", arrList[0]) | ||||||
| 			return | 			return | ||||||
| 		} | 		} | ||||||
| 		// 对象结构,递归处理 | 		// 对象结构,递归处理 | ||||||
| @ -141,5 +142,8 @@ func (oj *ownJson) getPath(root string, currentName string) string { | |||||||
| 	if root == "" { | 	if root == "" { | ||||||
| 		return currentName | 		return currentName | ||||||
| 	} | 	} | ||||||
|  | 	if currentName == "" { | ||||||
|  | 		return root | ||||||
|  | 	} | ||||||
| 	return root + "." + currentName | 	return root + "." + currentName | ||||||
| } | } | ||||||
|  | |||||||
| @ -13,7 +13,7 @@ import ( | |||||||
| ) | ) | ||||||
|  |  | ||||||
| func TestNewJson(t *testing.T) { | func TestNewJson(t *testing.T) { | ||||||
| 	sourceData := `{"name": "test", "age":18,"company":{"address": "Beijing", "name":"lala"},"index":[1,2,3,4], "deep":[{"name":"a"}]}` | 	sourceData := `{"name": "test", "age":18,"company":{"address": "Beijing", "name":"lala"},"index":[1,2,3,4], "deep":[[{"name":"a","age":20},{"name":"c"}], [{"name":"b"},{"name":"d"}]]}` | ||||||
| 	instance, iErr := NewJson(sourceData, &Option{XmlName: "ResponseData"}) | 	instance, iErr := NewJson(sourceData, &Option{XmlName: "ResponseData"}) | ||||||
| 	fmt.Println(iErr) | 	fmt.Println(iErr) | ||||||
| 	res, err := instance.Marshal("xml") | 	res, err := instance.Marshal("xml") | ||||||
|  | |||||||
		Reference in New Issue
	
	Block a user