2 using System.Collections.Generic;
3 using System.Collections.ObjectModel;
5 using System.Threading.Tasks;
6 using Newtonsoft.Json.Linq;
8 namespace Xamarin.Forms.Pages
10 public class JsonDataSource : BaseDataSource
12 readonly ObservableCollection<IDataItem> _dataItems = new ObservableCollection<IDataItem>();
13 Task _currentParseTask;
17 public JsonDataSource()
21 internal JsonDataSource(JToken rootToken)
23 ParseJsonToken(rootToken);
26 [TypeConverter(typeof(JsonSourceConverter))]
27 public JsonSource Source
29 get { return _source; }
37 if (value != null && _initialized)
39 _currentParseTask = ParseJson();
40 _currentParseTask.ContinueWith(t => { throw t.Exception; }, TaskContinuationOptions.OnlyOnFaulted);
45 protected override async Task<IList<IDataItem>> GetRawData()
49 Task task = _currentParseTask = ParseJson();
52 else if (_currentParseTask != null && _currentParseTask.IsCompleted == false)
53 await _currentParseTask;
57 protected override object GetValue(string key)
59 IDataItem target = _dataItems.FirstOrDefault(d => d.Name == key);
63 protected override bool SetValue(string key, object value)
65 IDataItem target = _dataItems.FirstOrDefault(d => d.Name == key);
68 _dataItems.Add(new DataItem(key, value));
71 if (target.Value == value)
77 object GetValueForJToken(JToken token)
81 case JTokenType.Object:
82 case JTokenType.Array:
83 return new JsonDataSource(token);
84 case JTokenType.Constructor:
85 case JTokenType.Property:
86 case JTokenType.Comment:
87 throw new NotImplementedException();
88 case JTokenType.Integer:
90 case JTokenType.Float:
93 case JTokenType.String:
95 case JTokenType.Boolean:
98 return (DateTime)token;
99 case JTokenType.Bytes:
100 return (byte[])token;
101 case JTokenType.Guid:
105 case JTokenType.TimeSpan:
106 return (TimeSpan)token;
112 async Task ParseJson()
120 string json = await Source.GetJson();
121 JToken jToken = JToken.Parse(json);
122 ParseJsonToken(jToken);
126 void ParseJsonToken(JToken token)
128 var jArray = token as JArray;
129 var jObject = token as JObject;
132 for (var i = 0; i < jArray.Count; i++)
134 JToken obj = jArray[i];
135 _dataItems.Add(new DataItem(i.ToString(), GetValueForJToken(obj)));
138 else if (jObject != null)
140 foreach (KeyValuePair<string, JToken> kvp in jObject)
142 _dataItems.Add(new DataItem(kvp.Key, GetValueForJToken(kvp.Value)));