Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

json: fix option sumtype handling #20186

Merged
merged 3 commits into from
Dec 19, 2023
Merged

Conversation

felipensp
Copy link
Member

@felipensp felipensp commented Dec 15, 2023

Fix #20181

import json

type Prices = []Price | Price

pub struct ShopResponseData {
    attributes Attributes
}

struct Attributes {
    price ?Prices
}

struct Price {
    net f64
}

fn main() {
    data := '{"attributes": {"price": [{"net": 1, "_type": "Price"}, {"net": 2, "_type": "Price"}]}}'
    entity := json.decode(ShopResponseData, data) or { panic(err) }

    data2 := '{"attributes": {"price": {"net": 1, "_type": "Price"}}}'
    entity2 := json.decode(ShopResponseData, data2) or { panic(err) }


	data3 := json.encode(ShopResponseData{attributes: Attributes{price: Prices([Price{net:1.2}])}})
	println(data3)
	entity3 := json.decode(ShopResponseData, data3) or { panic(err) }
	println(entity3)

    println(entity)
    println(entity2)
	
}

🤖[deprecated] Generated by Copilot at f83790b

Improve and fix json_no_inline_sumtypes flag for sumtypes. Add support for option sumtypes and struct variants in vlib/v/gen/c/json.v.

🤖[deprecated] Generated by Copilot at f83790b

  • Fix bug and simplify code for encoding sumtypes with json_no_inline_sumtypes flag by removing unnecessary else branch (link)
  • Use var_data variable instead of val prefix for encoding sumtype variants that are time.Time or other structs to make code more consistent and avoid errors (link)
  • Add branch to handle decoding option sumtypes with json_no_inline_sumtypes flag by wrapping variant value in _option_ok call (link)
  • Check JSON value type when decoding sumtype variants that are structs and return appropriate type and option wrapping (link, link)

@felipensp felipensp marked this pull request as ready for review December 18, 2023 12:47
@spytheman spytheman merged commit db6ae6e into vlang:master Dec 19, 2023
54 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

optional sumtype struct field builder error
2 participants