[Ethereum] Solidity return string not hex

contract-invocationjavascriptsoliditystringweb3js

Currently I'm using ether.camp to create a contract. At this stage it simply gets and stores some values. However when I try and get the values they are in bytes/hex even though the return type is string?

How do I convert this back to string in the solidity contract? I've tried How to convert a bytes32 to string but no luck

E.g storing "Hello World!" returns 0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000c48656c6c6f20576f726c64210000000000000000000000000000000000000000

   contract HelloWorld {
    struct Items {
       address id;
       string data;
    }

    mapping(address => Items) items;

    function getItem(address key) returns (string) {
      return items[key].data;
    }

    function addItem (address key, string data) returns (bool) {
        Items item = items[key];
        item.data = data;
    }

   }

 }

I can see in the ethercamp transactions side bar of the IDE the "Hello World!" is saved as a string but my getItem() just can't retrieve it?

Best Answer

Use web3.js like contractInstance.getItem.call(key).

Or mark getItem as constant: function getItem(address key) constant returns (string) and then you can use:

contractInstance.getItem(key)

web3.js will automatically decode the bytes for you. Contracts only have binary data, hex is a more compact way of viewing that data, and that's why you see hex. The binary data is also encoded according to an ABI, so that values can be distinguished, for example between what's just a number and a string.

Related Topic