有没有办法将JSON字符串解析为现有的Javascript对象: 假设我创建了这个对象:
var ClientState = function(){
this.userId ="";
this.telephoneState = "UNKNOWN";
this.agentState = "UNKNOWN";
this.muteState = "UNKNOWN";
this.number = "";
this.ready = false;
}
ClientState.prototype = {
doNastyStuff: function(){
//do something here
}
//other methods here
}
我有这个json通过电线:
{"userId":"xyz","telephoneState":"READY","agentState":"UNKNOWN","muteState":"MUTED","number":"","ready":false}
是否可以反序列化为上面指定的对象?这样我就可以使用它上面指定的所有方法了吗? 或者通常可以反序列化为特定的目标对象(不指定此目标对象中的反序列化)? (我知道我可以创建一个接受json或解析对象的构造函数。)
答案 0 :(得分:2)
是的!您可以使用Object.assign
用另一个对象覆盖对象的属性:
var ClientState = function() {
this.userId = "";
this.telephoneState = "UNKNOWN";
this.agentState = "UNKNOWN";
this.muteState = "UNKNOWN";
this.number = "";
this.ready = false;
}
var c = new ClientState();
console.log('prior assignment: ', c);
Object.assign(c, {
"userId": "xyz",
"telephoneState": "READY",
"agentState": "UNKNOWN",
"muteState": "MUTED",
"number": "",
"ready": false
});
console.log('after assignment: ', c);

请注意,它将通过匹配相应的键来覆盖源对象(第一个对象)与目标对象(第二个对象)的所有属性。目标对象中不存在的键在源对象中保持不变。
答案 1 :(得分:0)
这是你的想法吗?
function parseAs(targetClass, rawJSON) {
return Object.assign(new targetClass(), JSON.parse(rawJSON));
}
var clientState = parseAs(ClientState, '{"userId":"xyz"}');
我不认为有这样的原生JSON方法可以做到这一点,但你可以写一个像上面那样的函数。您甚至可以在JSON
类本身上定义它:
JSON.parseAs = function(targetClass, rawJSON) {
return Object.assign(new targetClass(), JSON.parse(rawJSON));
}
答案 2 :(得分:0)
如果要使用函数将对象值添加到实例属性:
function ClientState() {
this.userId = "";
this.telephoneState = "UNKNOWN";
this.agentState = "UNKNOWN";
this.muteState = "UNKNOWN";
this.number = "";
this.ready = false;
}
ClientState.prototype = {
doNastyStuff: function(json) {
const data = JSON.parse(json);
Object.assign(this, data);
}
}
const json = '{"userId":"xyz","telephoneState":"READY","agentState":"UNKNOWN","muteState":"MUTED","number":"","ready":false}';
const clientState = new ClientState();
clientState.doNastyStuff(json);
console.log(clientState);