01: /*
02: * MyGWT Widget Library
03: * Copyright(c) 2007, MyGWT.
04: * licensing@mygwt.net
05: *
06: * http://mygwt.net/license
07: */
08: package net.mygwt.ui.client.data;
09:
10: import java.util.Date;
11: import java.util.HashMap;
12: import java.util.Map;
13:
14: import com.google.gwt.i18n.client.DateTimeFormat;
15: import com.google.gwt.json.client.JSONArray;
16: import com.google.gwt.json.client.JSONBoolean;
17: import com.google.gwt.json.client.JSONNumber;
18: import com.google.gwt.json.client.JSONObject;
19: import com.google.gwt.json.client.JSONParser;
20: import com.google.gwt.json.client.JSONString;
21: import com.google.gwt.json.client.JSONValue;
22:
23: /**
24: * A <code>DataReader</code> implementation that reads JSON data using a
25: * <code>ModelType</code> definition and produces a set of <code>Model</code>
26: * instances.
27: */
28: public class JSONReader implements DataReader {
29:
30: private ModelType modelType;
31:
32: public JSONReader(ModelType modelType) {
33: this .modelType = modelType;
34: }
35:
36: public LoadResult read(Object data) {
37: JSONObject jsonRoot = (JSONObject) JSONParser
38: .parse((String) data);
39: JSONArray root = (JSONArray) jsonRoot.get(modelType.root);
40: int size = root.size();
41: DataList records = new DataList();
42: for (int i = 0; i < size; i++) {
43: JSONObject obj = (JSONObject) root.get(i);
44: Map values = new HashMap();
45: for (int j = 0; j < modelType.getFieldCount(); j++) {
46: DataField field = modelType.getField(j);
47: String map = field.map != null ? field.map : field.name;
48: JSONValue value = obj.get(map);
49:
50: if (value == null)
51: continue;
52: if (value.isArray() != null) {
53: // nothing
54: } else if (value.isBoolean() != null) {
55: boolean b = ((JSONBoolean) value).booleanValue();
56: values.put(field.name, new Boolean(b));
57: } else if (value.isNumber() != null) {
58: double d = ((JSONNumber) value).getValue();
59: values.put(field.name, new Double(d));
60: } else if (value.isObject() != null) {
61: // nothing
62: } else if (value.isString() != null) {
63: String s = ((JSONString) value).stringValue();
64: if (field.type != null) {
65: if (field.type.equals("date")) {
66: DateTimeFormat format = DateTimeFormat
67: .getFormat(field.format);
68: Date d = format.parse(s);
69: values.put(field.name, d);
70: }
71: } else {
72: values.put(field.name, s);
73: }
74:
75: } else if (value.isNull() != null) {
76: values.put(field.name, null);
77: }
78: }
79: records.add(new Model(values));
80: }
81: LoadResult result = new LoadResult();
82: result.data = records;
83: return result;
84: }
85: }
|