01: /*
02: * Copyright (C) 2003, 2004 Joe Walnes.
03: * Copyright (C) 2006, 2007 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 26. September 2003 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.converters.basic;
13:
14: import com.thoughtworks.xstream.converters.Converter;
15: import com.thoughtworks.xstream.converters.MarshallingContext;
16: import com.thoughtworks.xstream.converters.SingleValueConverter;
17: import com.thoughtworks.xstream.converters.UnmarshallingContext;
18: import com.thoughtworks.xstream.io.HierarchicalStreamReader;
19: import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
20:
21: /**
22: * Converts a char primitive or java.lang.Character wrapper to
23: * a String. If char is \0 the representing String is empty.
24: *
25: * @author Joe Walnes
26: * @author Jörg Schaible
27: */
28: public class CharConverter implements Converter, SingleValueConverter {
29:
30: public boolean canConvert(Class type) {
31: return type.equals(char.class) || type.equals(Character.class);
32: }
33:
34: public void marshal(Object source, HierarchicalStreamWriter writer,
35: MarshallingContext context) {
36: writer.setValue(toString(source));
37: }
38:
39: public Object unmarshal(HierarchicalStreamReader reader,
40: UnmarshallingContext context) {
41: String nullAttribute = reader.getAttribute("null");
42: if (nullAttribute != null && nullAttribute.equals("true")) {
43: return new Character('\0');
44: } else {
45: return fromString(reader.getValue());
46: }
47: }
48:
49: public Object fromString(String str) {
50: if (str.length() == 0) {
51: return new Character('\0');
52: } else {
53: return new Character(str.charAt(0));
54: }
55: }
56:
57: public String toString(Object obj) {
58: char ch = ((Character) obj).charValue();
59: return ch == '\0' ? "" : obj.toString();
60: }
61:
62: }
|