v icon indicating copy to clipboard operation
v copied to clipboard

[json][x.json2] Consider serializing enums as strings instead of integers

Open Zhomart opened this issue 2 years ago • 4 comments

Describe the feature

Currently both json and x.json2 serialize enums as integers. But it creates a problem when deserializing these values when the order of values of the enum changes - which can happen when devs change the order by sorting or add a new value in the beginning of enums.

Use Case

Please see this example. If MyEnum is created as enum MyEnum {foo bar}, then we generate a json from that. Later someone changes the order to enum MyEnum {bar foo}. Then the value of parsed enum is different.

pub enum MyEnum { bar foo }

fn main() {
	// Originally 
	// enum MyEnum { foo bar }
	val := 0 // MyEnum.foo

	q := unsafe { MyEnum(val) }
	
	match q {
		.foo { println('this is foo') }
		.bar { println('this is bar') }
	}
}

// It prints: 
//   this is bar

Proposed Solution

Instead of integers, vlang can serialize enums as strings, e.g.

println(json2.encode(MyEnum.foo))  // "foo"

Other Information

It also requires some changes to how enums work. There must be a way of creating enum value from strings.

example:

val := json.decode(str) // "foo"

enum_val := MyEnum(val)  // MyEnum.foo

Acknowledgements

  • [ ] I may be able to implement this feature request
  • [x] This feature might incur a breaking change

Version used

0.3.3

Environment details (OS name and version, etc.)

OS: macos, macOS, 13.1, 22C65 Processor: 8 cpus, 64bit, little endian, Apple M1 Pro CC version: Apple clang version 14.0.0 (clang-1400.0.29.202)

getwd: /Users/zhomart/vlang vmodules: /Users/zhomart/.vmodules vroot: /Users/zhomart/vlang vexe: /Users/zhomart/vlang/v vexe mtime: 2023-03-04 22:33:40 is vroot writable: true is vmodules writable: true V full version: V 0.3.3 1a48d08

Git version: git version 2.39.0 Git vroot status: weekly.2022.49-500-g1a48d08d .git/config present: true thirdparty/tcc status: thirdparty-macos-arm64 a668e5a0

Zhomart avatar Mar 05 '23 06:03 Zhomart

Excellent point about the long-term viability of serializing enums as ints.

JalonSolov avatar Mar 05 '23 14:03 JalonSolov

C# also does encode and decode of enums with strings.

danieldaeschle avatar Mar 09 '23 13:03 danieldaeschle

yeah sounds good

medvednikov avatar Mar 09 '23 15:03 medvednikov

json module already acts like this, afaik json2 must be changed. @enghitalo

felipensp avatar Apr 10 '23 19:04 felipensp