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.

pithhelmet
  • 2,222
  • 6
  • 35
  • 60

4 Answers4

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());
Joao Lopes
  • 936
  • 5
  • 9
1

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

Try to assign to this.firstName instead.

huysentruitw
  • 27,376
  • 9
  • 90
  • 133
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.

melpomene
  • 84,125
  • 8
  • 85
  • 148
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);
pithhelmet
  • 2,222
  • 6
  • 35
  • 60