如何序列化数组?

时间:2011-03-28 22:21:56

标签: javascript jquery json serialization fullcalendar

我在jQuery的fullcallendar插件中序列化事件数组时遇到了问题。

问题是每个事件对象都包含属性“Source”,它具有对事件的自引用。

  • 我需要遍历数组,创建一个新对象,传递我需要序列化的元素和属性(跳过不必要的元素),然后将序列化应用于该对象。
  • 或者我必须找到一种方法来“按原样”序列化它。

你会先帮我解决语法问题(因为我在jQuery和javascript方面不太好), 或者在第二时间以正确的方式告诉我。

我认为我需要javascript中的东西,这相当于c#的

public class Event{
   public string Name;
   public Event  Source;
}

public class EventNoSource{
   public string Name;
}

var events = new List<Event>();

var ev1 = new Event{Name = "ev1"};
ev1.Source = ev1;
events.Add(ev1);

var ev2 = new Event{Name = "ev2"};
ev2.Source = ev2;
events.Add(ev2);

var eventsPlain = new List<EventNoSource>();
events.ForEach(x=> eventsPlain.Add(new EventNoSource{Name = x.Name}));

4 个答案:

答案 0 :(得分:4)

来自jQuery doc。

var myObject = {
  a: {
    one: 1, 
    two: 2, 
    three: 3
  }, 
  b: [1,2,3]
};
var recursiveEncoded = $.param(myObject);
var recursiveDecoded = decodeURIComponent($.param(myObject));

alert(recursiveEncoded);
alert(recursiveDecoded);

尝试执行它。这是你需要的吗?

如果你已经在某个地方的代码中定义了$ variable(因为使用了其他工具),你可以尝试使用这个调用:

jQuery.param(myObject)

答案 1 :(得分:1)

我开发了一个jQuery插件,它将元素类型,数组和对象序列化为DOM元素。不过,我仍然不知道如何序列化闭包。

(function($) {

$.identity = function(key, value) {
    return value;
};

$.fn.tag = function(index) {
    return this
    .get(index || 0)
    .nodeName
    .toLowerCase();
};

$.fn.append2 = function(collection, callback) {
    var $this = this;

    // The default callback does nothing.
    callback = callback || $.identity;

    // Apply the callback to each element of the
    // collection, and append the result.
    $.each(collection, function(key, value) {
        $this.append(callback(key, value));
    });

    return this;
};

$.serialize = function(key, value) {
    if (!value) {
        // No arguments? Return empty selector.
        if (!key && key !== 0)
            return $();

        // Swap arguments.
        value = key;
        key   = null;
    }

    var $this = (typeof value === 'object')

        // Serialize into <div>.
        ? $('<div>')
        .append2(value, $.serialize)
        .addClass(value.constructor === Array
            ? 'array' : '')

        // Serialize into <input>.
        : $('<input>').val(value);

    // Name the element.
    if (key != null)
        $this.attr('name', key);

    return $this;
};

$.fn.deserialize = function() {
    if (this.length !== 1)
        return null;

    var tag = this.tag();

    // Deserialize into elementary value?
    if (tag === 'input')
        return this.val();

    // Unable to deserialize?
    if (tag !== 'div')
        return null;

    // Deserialize into array/object.
    var array = this.hasClass('array');
    var res   = array ? [] : {};

    // Deserialize members into sub-elements.
    this
    .children('div[name],input[name]')
    .each(function() {
        var $this = $(this);
        var name  = $this.attr('name');
        var value = $this.deserialize();
        res[array ? +name : name] = value;
    });

    return res;
};

})(jQuery);

以下是一个例子:

文件1: test.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <script type="text/javascript" src="latest-jquery.js"></script>
  <script type="text/javascript" src="test.js"></script>
  <title>Example</title>
</head>

<body>
  <div style="display: none" id="info">
    <input name="name" value="Eduardo León"/>
    <input name="age" value="23"/>
    <input name="degree" value="Systems Engineer"/>
    <div class="array" name="relatives">
      <div name="0">
        <input name="relationship" value="Significant Other"/>
        <input name="name" value="Kelly Cruz"/>
      </div>
      <div name="1">
        <input name="relationship" value="Son"/>
        <input name="name" value="Mauricio León"/>
      </div>
    </div>
  </div>
</body>

</html>

文件2: test.js

$(document).ready(function() {
    var $sel = $('#info');

    // Retrieve information contained in
    // the original HTML document.
    var info = $sel.deserialize();
    alert(info.name);
    alert(info.age);
    alert(info.degree);
    alert(info.relatives.length);
    $.each(info.relatives, function(index, relative) {
        alert(relative.relationship);
        alert(relative.name);
    });

    // Update information with a list of comics.
    $sel.append($.serialize('comics', [
        {name: 'xkcd',            author: 'Randall Munroe'},
        {name: 'Dinosaur Comics', author: 'Ryan North'}
    ]));

    // Re-retrieve the information, including the list of comics.
    info = $sel.deserialize();
    $.each(info.comics, function(index, comic) {
        alert(comic.name);
        alert(comic.author);
    });
});

答案 2 :(得分:1)

这是我一直想用fullcalendar改变的东西。我想删除源属性,并通过方法使其可访问。如果您想将此添加到问题跟踪器,请执行以下操作: http://code.google.com/p/fullcalendar/issues/list

答案 3 :(得分:0)

 $.each(events, function(index, value) { 
                                         var ev = new Object();
                                         ev.name = value.name;
                                        }