View Javadoc

    1   /**
    2    * Copyright (c) 2008-2011, http://www.snakeyaml.org
    3    *
    4    * Licensed under the Apache License, Version 2.0 (the "License");
    5    * you may not use this file except in compliance with the License.
    6    * You may obtain a copy of the License at
    7    *
    8    *     http://www.apache.org/licenses/LICENSE-2.0
    9    *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  package org.yaml.snakeyaml.issues.issue127;
    17
    18  import java.util.LinkedHashMap;
    19  import java.util.Map;
    20
    21  import junit.framework.TestCase;
    22
    23  import org.yaml.snakeyaml.Yaml;
    24  import org.yaml.snakeyaml.nodes.Node;
    25  import org.yaml.snakeyaml.nodes.Tag;
    26  import org.yaml.snakeyaml.representer.Represent;
    27  import org.yaml.snakeyaml.representer.Representer;
    28
    29  public class NullAliasTest extends TestCase {
    30      private static final Tag MY_TAG = new Tag("tag:example.com,2011:bean");
    31
    32      public void testRespresenter() {
    33          Bean bean = new Bean();
    34
    35          bean.setA("a"); // leave b null
    36          Yaml yaml = new Yaml(new BeanRepresenter());
    37          String output = yaml.dump(bean);
    38          assertEquals("!<tag:example.com,2011:bean>\na: a\nb: null\n", output);
    39      }
    40
    41      class BeanRepresenter extends Representer {
    42          public BeanRepresenter() {
    43              this.representers.put(Bean.class, new RepresentBean());
    44          }
    45
    46          private class RepresentBean implements Represent {
    47              public Node representData(Object data) {
    48                  Bean bean = (Bean) data;
    49                  Map<String, Object> fields = new LinkedHashMap<String, Object>(2);
    50                  fields.put("a", bean.getA());
    51                  fields.put("b", bean.getB());
    52                  return representMapping(MY_TAG, fields, false);
    53              }
    54          }
    55      }
    56  }