1

I would like to serialize/stringify a javascript object that can be passed between browsers as a string using signalr

The signalr portion is working, as i can send and receive chat messages.

This is my simple test rig

function UserObject() {
  var _firstName = 't';
  this.getFirstName = function () {
    return _firstName;
  }
  this.setFirstName = function (value) {
    _firstName = value;
  }
}

var userObject = new UserObject();
console.log(userObject.getFirstName());
userObject.setFirstName('tony');
console.log(JSON.stringify(userObject));
console.log("First Name: " + userObject.getFirstName());

This is the results that i am receiving.

> "t"
> "{}"
> "First Name: tony"

Why is the console.log(JSON.stringify(userObject)) failing? When i can set the value, reset the value and not see the value when i try to view the object.

1

4 Answers 4

2

It's failing because you only have private variables.

Here's with public properties.

function UserObject() {
  var _firstName = 't';
  this.getFirstName = function () {
    return this.firstName || _firstName;
  }
  this.setFirstName = function (value) {
    this.firstName = value;
  }
}

var userObject = new UserObject();
console.log(userObject.getFirstName());
userObject.setFirstName('tony');
console.log(JSON.stringify(userObject));
console.log("First Name: " + userObject.getFirstName());

Sign up to request clarification or add additional context in comments.

Comments

1

Your value is stored in _firstName, which is a local variable in the UserObject function. It's not stored in the object, so serializing the object won't show it.

The only thing stored in your object is two functions (getFirstName, setFirstName), but JSON can't represent functions.

That's why the JSON result shows an empty object.

Comments

1

Because your UserObject doesn't have any public field to serialize.

Try to assign to this.firstName instead.

Comments

0

This is what i went with....

    var UserObject = {
        firstName: '',
        lastName: ''
    };
    UserObject.firstName = 'tony';
    var myObjStr = JSON.stringify(UserObject);
    console.log(myObjStr);
    var uo = JSON.parse(myObjStr);
    console.log(uo);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.