ballerina-platform / ballerina-library

The Ballerina Library
https://ballerina.io/learn/api-docs/ballerina/
Apache License 2.0
137 stars 65 forks source link

`jsondata:parseAsType()` return a error when the given type is readonly #7253

Open lnash94 opened 2 weeks ago

lnash94 commented 2 weeks ago

Description: The below sample returns an error while parsing using jsondata:parserAsType(), this error occurred when given data type has data type with readonly ,

import ballerina/io;
import ballerina/data.jsondata;

public type RestaurantNew record {|
    *Restaurant;
    [int, string, decimal, float, User] address;
|};

public enum MenuType {
    BREAK_FAST,
    LUNCH,
    DINNER
}

public type MenuItem record {|
    int _id;
    string name;
    string description;
    decimal price;
|};

public type Menu record {|
    int _id;
    MenuType 'type;
    MenuItem[] items;
|};

public type Restaurant record {|
    string name;
    string city;
    string description;
    Menu[] menus;
|};

public type User readonly & record {|
    int id;
    int age;
|};

public function main() returns jsondata:Error? {
    json restaurant = {
        name: "name1",
        city: "city1",
        address: [10, "street", 9, 12.45, {id: 4012, age: 36}],
        description: "description1",
        menus: [
            {
                _id: 5,
                'type: "LUNCH",
                items: []
            }
        ]
    };
    RestaurantNew r = check jsondata:parseAsType(restaurant);

    io:println(r);
}

Steps to reproduce: Run the above given sample

Affected Versions: 2201.10.1 OS, DB, other environment details and versions:

Related Issues (optional):

Suggested Labels (optional):

Suggested Assignees (optional):

lnash94 commented 2 weeks ago

This issue is a blocker for the module http , jsondata APIs migration in u11. https://github.com/ballerina-platform/module-ballerina-http/pull/2168 And provide this support : https://github.com/ballerina-platform/ballerina-library/issues/4870#issuecomment-2262151011

SasinduDilshara commented 2 weeks ago

The simplest version of the error

import ballerina/io;
import ballerina/data.jsondata;
public type User readonly & record {|
    int id;
|};

public function main() returns jsondata:Error? {
    json user2 = {id: 4012};
    User r2 = check jsondata:parseAsType(user2);
    io:println(r2);
}
lnash94 commented 1 week ago

We received an error for the below scenario as well

type DDPerson record {|
    readonly int id;
|};

DDPerson rs = check jsondata:parseAsType({id: 10});
error: {ballerina}TypeCastError {"message":"incompatible types: 'error' cannot be cast to '(anydata|data.jsondata:Error)'"}
        at ballerina.data.jsondata.0:parseAsType(json_api.bal:24)