01: /*
02: * Copyright (C) 2003, 2004, 2005 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 03. October 2003 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.converters.collections;
13:
14: import com.thoughtworks.xstream.converters.MarshallingContext;
15: import com.thoughtworks.xstream.converters.UnmarshallingContext;
16: import com.thoughtworks.xstream.io.HierarchicalStreamReader;
17: import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
18: import com.thoughtworks.xstream.mapper.Mapper;
19:
20: import java.lang.reflect.Array;
21: import java.util.ArrayList;
22: import java.util.Iterator;
23: import java.util.List;
24:
25: /**
26: * Converts an array of objects or primitives to XML, using
27: * a nested child element for each item.
28: *
29: * @author Joe Walnes
30: */
31: public class ArrayConverter extends AbstractCollectionConverter {
32:
33: public ArrayConverter(Mapper mapper) {
34: super (mapper);
35: }
36:
37: public boolean canConvert(Class type) {
38: return type.isArray();
39: }
40:
41: public void marshal(Object source, HierarchicalStreamWriter writer,
42: MarshallingContext context) {
43: int length = Array.getLength(source);
44: for (int i = 0; i < length; i++) {
45: Object item = Array.get(source, i);
46: writeItem(item, context, writer);
47: }
48:
49: }
50:
51: public Object unmarshal(HierarchicalStreamReader reader,
52: UnmarshallingContext context) {
53: // read the items from xml into a list
54: List items = new ArrayList();
55: while (reader.hasMoreChildren()) {
56: reader.moveDown();
57: Object item = readItem(reader, context, null); // TODO: arg, what should replace null?
58: items.add(item);
59: reader.moveUp();
60: }
61: // now convertAnother the list into an array
62: // (this has to be done as a separate list as the array size is not
63: // known until all items have been read)
64: Object array = Array.newInstance(context.getRequiredType()
65: .getComponentType(), items.size());
66: int i = 0;
67: for (Iterator iterator = items.iterator(); iterator.hasNext();) {
68: Array.set(array, i++, iterator.next());
69: }
70: return array;
71: }
72: }
|