Skip to content

json: fix option sumtype handling - #20186

Merged
spytheman merged 3 commits into
vlang:masterfrom
felipensp:fix_json_sumtypes
Dec 19, 2023
Merged

spytheman merged 3 commits into
vlang:masterfrom
felipensp:fix_json_sumtypes

Conversation

@felipensp

@felipensp felipensp commented Dec 15, 2023 •

Copy link
Copy Markdown
Member

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
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