1 /** 2 * Copyright (c) 2008, SnakeYAML 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 * in compliance with the License. You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software distributed under the License 10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 * or implied. See the License for the specific language governing permissions and limitations under 12 * the License. 13 */ 14 package examples; 15 16 import static org.junit.Assert.assertEquals; 17 18 import org.junit.Test; 19 import org.yaml.snakeyaml.TypeDescription; 20 import org.yaml.snakeyaml.Yaml; 21 22 public class KeyIsNotTheSameAsFieldTest { 23 24 public static class Param { 25 26 private String name; 27 private String inputPart; 28 private String more; 29 getName()30 public String getName() { 31 return name; 32 } 33 setName(String name)34 public void setName(String name) { 35 this.name = name; 36 } 37 getInputPart()38 public String getInputPart() { 39 return inputPart; 40 } 41 setInputPart(String inputPart)42 public void setInputPart(String inputPart) { 43 this.inputPart = inputPart; 44 } 45 getMore()46 public String getMore() { 47 return more; 48 } 49 setMore(String more)50 public void setMore(String more) { 51 this.more = more; 52 } 53 } 54 55 @Test loadFromStr()56 public void loadFromStr() { 57 Param p = createYaml().loadAs("name: \"Test\"\ninput_part: \"abc\"\ndefault: \"some value\"", 58 Param.class); 59 60 assertEquals("Test", p.getName()); 61 assertEquals("abc", p.getInputPart()); 62 assertEquals("some value", p.getMore()); 63 } 64 65 @Test dumpNload()66 public void dumpNload() { 67 Param realParam = new Param(); 68 realParam.setName("Test"); 69 realParam.setInputPart("abc"); 70 realParam.setMore("some value"); 71 72 String yamlStr = createYaml().dump(realParam); 73 Param loadedParam = createYaml().loadAs(yamlStr, Param.class); 74 75 assertEquals(realParam.getName(), loadedParam.getName()); 76 assertEquals(realParam.getInputPart(), loadedParam.getInputPart()); 77 assertEquals(realParam.getMore(), loadedParam.getMore()); 78 } 79 createYaml()80 private Yaml createYaml() { 81 TypeDescription paramDesc = new TypeDescription(Param.class); 82 paramDesc.substituteProperty("input_part", String.class, "getInputPart", "setInputPart"); 83 paramDesc.substituteProperty("default", String.class, "getMore", "setMore"); 84 85 /* 86 * Need to exclude real properties. Otherwise we get them in dump in addition to "generated" 87 * ones: 88 * 89 * {input_part: ?1?, default: ?2?, inputPart: ?1?, more: ?2?, name: ???} 90 * 91 * not just 92 * 93 * {input_part: ?1?, default: ?2?, name: ???} 94 */ 95 paramDesc.setExcludes("inputPart", "more"); 96 97 Yaml yaml = new Yaml(); 98 yaml.addTypeDescription(paramDesc); 99 return yaml; 100 } 101 } 102