9

How can I return a dynamic string array? I came across serialization and deserialization. How can I serialize and deserialize dynamic string array ?

pragma solidity ^0.5.0;

contract Abc{
    string[] st;

    function add(string memory newValue) public {
        st.push(newValue);
    }

    // return st

3 Answers 3

6

As of Solidity 0.7.5 the ABIEncoderV2 is not experimental anymore and can be selected using the pragma directive.

This gives native support for returning dynamic string arrays from functions.

pragma solidity ^0.8.2;
pragma abicoder v2;

contract Abc {
    string[] st;

    function add(string memory newValue) public {
        st.push(newValue);
    }

    function getSt() public view returns (string[] memory) {
        return st;
    }
}

On a side note, starting with Solidity 0.8.0 abicoder v2 is enabled by default and the pragma directive can therefore be omitted.

0
3

Actually there is not support from solidity for returning an array of strings as described here:

Return dynamic array of string

You can fix it adopting this workaround described here:

Deserialize a string

2

You need to use ABIEncoderV2:

pragma experimental ABIEncoderV2;

contract Foo {
  string [] private strings;

  function addString (string memory str) public {
    strings.push (str);
  }

  function getStrings () public view returns (string [] memory) {
    return strings;
  }
}

See documentation for details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.