Skip to content

Commit a4c0f5e

Browse files
committed
added custom json tag support
1 parent 90155a4 commit a4c0f5e

File tree

2 files changed

+32
-5
lines changed

2 files changed

+32
-5
lines changed

typescriptify/typescriptify.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ const (
1616
tsDocTag = "ts_doc"
1717
tsTransformTag = "ts_transform"
1818
tsType = "ts_type"
19+
jsonTag = "json"
1920
tsConvertValuesFunc = `convertValues(a: any, classs: any, asMap: boolean = false): any {
2021
if (!a) {
2122
return a;
@@ -86,6 +87,7 @@ type TypeScriptify struct {
8687
BackupDir string // If empty no backup
8788
DontExport bool
8889
CreateInterface bool
90+
CustomJsonTag string
8991
customImports []string
9092

9193
structTypes []StructType
@@ -219,6 +221,11 @@ func (t *TypeScriptify) WithSuffix(s string) *TypeScriptify {
219221
return t
220222
}
221223

224+
func (t *TypeScriptify) WithCustomJsonTag(tag string) *TypeScriptify {
225+
t.CustomJsonTag = tag
226+
return t
227+
}
228+
222229
func (t *TypeScriptify) Add(obj interface{}) *TypeScriptify {
223230
switch ty := obj.(type) {
224231
case StructType:
@@ -518,7 +525,11 @@ func (t *TypeScriptify) getFieldOptions(structType reflect.Type, field reflect.S
518525

519526
func (t *TypeScriptify) getJSONFieldName(field reflect.StructField, isPtr bool) string {
520527
jsonFieldName := ""
521-
jsonTag := field.Tag.Get("json")
528+
tag := jsonTag
529+
if t.CustomJsonTag != "" {
530+
tag = t.CustomJsonTag
531+
}
532+
jsonTag := field.Tag.Get(tag)
522533
if len(jsonTag) > 0 {
523534
jsonTagParts := strings.Split(jsonTag, ",")
524535
if len(jsonTagParts) > 0 {

typescriptify/typescriptify_test.go

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@ import (
1616

1717
type Address struct {
1818
// Used in html
19-
Duration float64 `json:"duration"`
20-
Text1 string `json:"text,omitempty"`
19+
Duration float64 `json:"duration" custom:"durationCustom"`
20+
Text1 string `json:"text,omitempty" custom:"textCustom,omitempty"`
2121
// Ignored:
22-
Text2 string `json:",omitempty"`
23-
Text3 string `json:"-"`
22+
Text2 string `json:",omitempty" custom:",omitempty"`
23+
Text3 string `json:"-" custom:"-"`
2424
}
2525

2626
type Dummy struct {
@@ -1010,3 +1010,19 @@ func TestTypescriptifyComment(t *testing.T) {
10101010
}`
10111011
testConverter(t, converter, false, desiredResult, nil)
10121012
}
1013+
1014+
func TestTypescriptifyCustomJsonTag(t *testing.T) {
1015+
t.Parallel()
1016+
1017+
converter := New().WithCustomJsonTag("custom")
1018+
1019+
converter.AddType(reflect.TypeOf(Address{}))
1020+
converter.CreateConstructor = false
1021+
converter.BackupDir = ""
1022+
1023+
desiredResult := `export class Address {
1024+
durationCustom: number;
1025+
textCustom?: string;
1026+
}`
1027+
testConverter(t, converter, false, desiredResult, nil)
1028+
}

0 commit comments

Comments
 (0)