使用javascript,如何转换为JSON,类似Java-POJO的类?

时间:2014-10-13 11:27:09

标签: javascript json pojo stringify

我想在我的JS项目中使用类似Java-POJO的类:只有私有字段,getter和setter。

function Event() {
var homeTeam;
var awayTeam;
var id;
var singleBets = [];
var bet;

...

this.getHomeTeam = function(){
    return homeTeam;
}
this.setHomeTeam = function(data){
    homeTeam = data;
}

this.getAwayTeam = function(){
    return awayTeam;
}
this.setAwayTeam = function(data){
    awayTeam = data;
}

this.getId = function(){
    return id;
}
this.setId = function(data){
    id = data;
}

this.getSingleBets = function(){
    return singleBets;
}
this.setSingleBets = function(data){
    singleBets = data;
}

this.getBet = function(){
    return bet;
}
this.setBet = function(data){
    bet = data;
}

}

我会在JSON字符串中转换类似Java-POJO的类以将其发送到服务器。 我不能使用JSON.stringify(myClass),因为字段是私有的。 所以我认为使用像这样的递归方法......

var myJsonParse = function(data){
    var result = "";
    for(var propertyName in data) {
        var method = propertyName;
        if (method.substring(0,3)=="get"){
            ... data[propertyName].call() ...
        }
    }
    return result;
}

...但在我花了很多时间写它之前,我想问你是否有更好的方法来转换JSON中类似Java-POJO的对象。 谢谢。

更新#1

我为自己感到羞耻!这是我的工作(但绝对是暂时的)解决方案:

this.toJSON = function() {
    var bettableEventsString =  [];
    for (var i = 0, len = bettableEvents.length; i < len; i++) {
        bettableEventsString[i] = bettableEvents[i].toJSON();
    }
    var result = JSON.stringify({
        userId: userId,
        championshipDayId: championshipDayId,
        championshipDayName: championshipDayName
    });

    result = result.substring(0, result.length-1);
    result += ',\n  "bettableEvents" : [ ' + bettableEventsString + " ] ";
    result += " } "

    return result;
}

1 个答案:

答案 0 :(得分:1)

我能想到的唯一简单方法是添加导出方法:

this.toJSON = function() {
    return JSON.stringify({
        homeTeam: homeTeam,
        awayTeam: awayTeam,
        id: id,
        // etc...
    });
}