0

How can I deserialize a JSON string into an sObject in a VF page? I don't want to use a controller so I'm looking for the right approach to do this on the client side only. Any ideas?

2
  • JSON.parse is available in modern browsers. Is that sufficient? Why the "into an sObject" in the question? – Keith C Oct 15 '14 at 8:27
  • I want to insert it to the database using sforce.conection.insert() – Dedo Oct 15 '14 at 11:22
1

If the JSON string has names that exactly match the SObject field names then you can use code like this:

var s = '{"Field1__c" : "Hello", "Field2__c": "World"}';
var o = JSON.parse(s);
var sob = new sforce.SObject('YourSObjectType__c');
for (var key in o) {
    if (o.hasOwnProperty(key)) {
        sob[key] = o[key];
    }
}
var result = sforce.connection.insert([sob]);

If the names do not match, instead of the loop you will need a series of assignments:

sob.Field1__c = o.JsonName1;
sob.Field2__c = o.JsonName2;
...
2
  • thanks, one question: is your iterating over (key in o(, is there any case where o.hasOwnProperty(key) is false? – Dedo Oct 16 '14 at 14:48
  • @Dedo Probably not in this case as I think JSON.parse creates a simple object with no prototype (though to be sure you would need to research or test against all browsers). Personally I'd leave it in. – Keith C Oct 16 '14 at 15:25
-3

You have create a wrapper as per the Json string format and then You can deserialize it .

1
  • 2
    Please elaborate your answer. It is not helpful in its current form. Please describe what you mean by wrapper and where the deserialization should take place. – Alexander Johannes Oct 15 '14 at 7:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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