ballerina

How to convert a string array received as an http post response to a record array in Ballerina?


I have the following code defining the record type Building.

public type Coordinate record {|
    float longitude;
    float latitude;
|};

public type Campus record {|
    string code;
    string name;
|};

public type Site record {|
    string location;
|};

public type Building record {
    string code;
    string address;
    Site site;
    Campus campus;
    Coordinate coordinate;
};

I am unable to convert the given string to Building[] as I have done below.

service / on ln {
    isolated resource function get test() returns anydata|error?
    {
        json mockedResponse = "[{\"site\": {\"location\": \"Winterthur\"}, \"campus\": {\"code\": \"T\", \"name\": \"Technikumstrasse\"}, \"code\": \"TD\", \"address\": \"Obere Kirchgasse 2, 8500 Winterthur\", \"coordinate\": {\"longitude\": 8.729426, \"latitude\": 47.498449}}, {\"site\": {\"location\": \"Winterthur\"}, \"campus\": {\"code\": \"T\", \"name\": \"Technikumstrasse\"}, \"code\": \"TH\", \"address\": \"Hauptgeb\\u00e4ude, 8500 Winterthur\",\"coordinate\": {\"longitude\": 8.729357, \"latitude\": 47.497303}}]";
        json response = <json> check mockedResponse.cloneWithType(json);
        Building[] buildings = <Building[]> check response.cloneWithType();

        foreach Building building in buildings {
            io:print(building.address);
        }
    }
}

Solution

  • You can directly use the fromJsonStringWithType() method to convert the string to Building[] here.

    string mockedResponse = "[{\"site\": {\"location\": \"Winterthur\"}, \"campus\": {\"code\": \"T\", \"name\": \"Technikumstrasse\"}, \"code\": \"TD\", \"address\": \"Obere Kirchgasse 2, 8500 Winterthur\", \"coordinate\": {\"longitude\": 8.729426, \"latitude\": 47.498449}}, {\"site\": {\"location\": \"Winterthur\"}, \"campus\": {\"code\": \"T\", \"name\": \"Technikumstrasse\"}, \"code\": \"TH\", \"address\": \"Hauptgeb\\u00e4ude, 8500 Winterthur\",\"coordinate\": {\"longitude\": 8.729357, \"latitude\": 47.497303}}]";
    Building[] buildings = check mockedResponse.fromJsonStringWithType();
    
    foreach Building building in buildings {
      io:print(building.address);
    }
    

    check,

    [1] fromJsonStringWithType