public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JToken value = null; var response = new FindConnectedObjectsResponse(); // status var json = JObject.ReadFrom(reader) as JObject; json.TryGetValue("status", out value); response.Status = serializer.Deserialize<Status>(value.CreateReader()); if (response.Status.IsSuccessful == false) return response; json.Remove("status"); // paging info // Extract paging info json.TryGetValue("paginginfo", out value); response.PagingInfo = serializer.Deserialize<PagingInfo>(value.CreateReader()); json.Remove("paginginfo"); // extract parent label json.TryGetValue("parent", out value); var parentLabel = value.ToString(); // Extract graph node. json.TryGetValue("nodes", out value); if (value.Type != JTokenType.Null) { var nodes = value.Values<JObject>(); ParseNodes(response, parentLabel, nodes, serializer); } else response.Nodes = new List<GraphNode>(); return response; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { string displayName = string.Empty; string address = string.Empty; while (reader.Read()) { var tokenType = reader.TokenType; if (reader.TokenType == JsonToken.PropertyName) { var val = (reader.Value as string )?? string.Empty; if (val == "DisplayName") { displayName = reader.ReadAsString(); } if (val == "Address") { address = reader.ReadAsString(); } } if (reader.TokenType == JsonToken.EndObject) { break; } } var mailAddress = new MailAddress(address, displayName); return mailAddress; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var reference = SupportedTypes[objectType].Invoke(); serializer.Populate(reader, reference); return reference; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.String) { return null; } var instance = Activator.CreateInstance(objectType) as ISafeEnum; if (instance == null) return null; var enumType = objectType.GetGenericArguments()[0]; var value = reader.Value as string; try { if (value == null) { instance.Value = null; } else { instance.Object = Enum.Parse(enumType, value, true); } } catch (Exception) { instance.Value = value; } return instance; }
/// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader" /> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var result = new ItemOrders(); serializer.Converters.Add(new EmdRowCollectionJsonConverter<ItemOrders.ItemOrderEntry>()); result.Orders = serializer.Deserialize<EmdRowCollection<ItemOrders.ItemOrderEntry>>(reader); return result; }
//TODO: This method can be removed if we used DateTimeOffsets instead public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { try { object o = base.ReadJson(reader, objectType, existingValue, serializer); //This is required because DateTime is really bad at parsing RFC1123 dates in C#. Basically it parses the value but //doesn't attach a DateTimeKind to it (even though RFC1123 specification says that the "Kind" should be UTC. This results //in a DateTime WITHOUT a DateTimeKind specifier, which is bad bad bad. We do the below in order to force the DateTimeKind //of the resulting DateTime to be DateTimeKind.Utc since that is what the RFC1123 specification implies. //See: http://stackoverflow.com/questions/1201378/how-does-datetime-touniversaltime-work //See: http://stackoverflow.com/questions/16442484/datetime-unspecified-kind DateTime? time = o as DateTime?; if (time.HasValue && time.Value.Kind == DateTimeKind.Unspecified) { time = DateTime.SpecifyKind(time.Value, DateTimeKind.Utc); } return time; } catch (FormatException ex) { throw new JsonException("Unable to deserialize a Date.", ex); } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var relations = new Relations(); var jToken = JToken.ReadFrom(reader); foreach (JProperty jProperty in jToken.Where(_ => _.GetType() == typeof(JProperty)).Cast<JProperty>()) { if (jProperty.Value.GetType() == typeof (JArray)) { var links = serializer.Deserialize<Link[]>(jProperty.Value.CreateReader()); foreach (var link in links) { relations.Add(link); link.Rel = jProperty.Name; } } else { var link = serializer.Deserialize<Link>(jProperty.Value.CreateReader()); link.Rel = jProperty.Name; relations.Add(link); } } return relations; }
public static Object _ReadValue(Type ValueType, JsonReader Reader, MudObject Owner) { Object r = null; if (Reader.TokenType == JsonToken.String) { r = Reader.Value.ToString(); Reader.Read(); } else if (Reader.TokenType == JsonToken.Integer) { r = Convert.ToInt32(Reader.Value.ToString()); Reader.Read(); } else if (Reader.TokenType == JsonToken.Boolean) { r = Convert.ToBoolean(Reader.Value.ToString()); Reader.Read(); } else { PersistentValueSerializer serializer = null; if (ValueType != null && PersistentValueSerializer.GlobalSerializers.TryGetValue(ValueType.Name, out serializer)) return serializer.ReadValue(ValueType, Reader, Owner); else if (Reader.TokenType == JsonToken.StartObject) { Reader.Read(); if (Reader.TokenType != JsonToken.PropertyName || Reader.Value.ToString() != "$type") throw new InvalidOperationException(); Reader.Read(); if (!PersistentValueSerializer.GlobalSerializers.TryGetValue(Reader.Value.ToString(), out serializer)) throw new InvalidOperationException(); Reader.Read(); Reader.Read(); r = serializer.ReadValue(ValueType, Reader, Owner); Reader.Read(); } else throw new InvalidOperationException(); } return r; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var tokenArray = JToken.ReadFrom(reader); var children = new List<IChartOfAccountChild>(); foreach (var token in tokenArray) { string type = token["type"].Value<string>(); if (type == AccountGroup.typeName) { var accountGroup = JsonConvert.DeserializeObject<AccountGroup>(token.ToString()); children.Add(accountGroup); } if (type == AccountIntervalGroup.typeName) { var accountIntervalGroup = JsonConvert.DeserializeObject<AccountIntervalGroup>(token.ToString()); children.Add(accountIntervalGroup); } } return children; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var text = reader.Value.ToString(); //MvxTrace.Trace("About to parse {0}", text); return DateTime.ParseExact(text, DateTimeFormat, CultureInfo.InvariantCulture); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue , JsonSerializer serializer) { var token = JToken.Load(reader); if (token.Values<string>() == null) return null; var list = token.Values<string>(); var tags = new List<TagStatic>(); foreach (var str in list) { switch (str) { case "Fighter": tags.Add(TagStatic.Fighter); break; case "Tank": tags.Add(TagStatic.Tank); break; case "Mage": tags.Add(TagStatic.Mage); break; case "Assassin": tags.Add(TagStatic.Assassin); break; case "Support": tags.Add(TagStatic.Support); break; case "Marksman": tags.Add(TagStatic.Marksman); break; } } return tags; }
private object ProcessToken(JsonReader reader) { // Recursively processes a token. This is required for elements that next other elements. object processedObject = null; if (reader.TokenType == JsonToken.StartObject) { Dictionary<string, object> dictionaryValue = new Dictionary<string, object>(); while (reader.Read() && reader.TokenType != JsonToken.EndObject) { string elementKey = reader.Value.ToString(); reader.Read(); dictionaryValue.Add(elementKey, ProcessToken(reader)); } processedObject = dictionaryValue; } else if (reader.TokenType == JsonToken.StartArray) { List<object> arrayValue = new List<object>(); while (reader.Read() && reader.TokenType != JsonToken.EndArray) { arrayValue.Add(ProcessToken(reader)); } processedObject = arrayValue.ToArray(); } else { processedObject = reader.Value; } return processedObject; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return null; } List<DotaSchemaItem> leagues = new List<DotaSchemaItem>(); JToken t = JToken.Load(reader); var properties = t.Children<JProperty>(); foreach (var item in properties) { JObject o = (JObject)item.Value; bool isLeague = o["prefab"] != null && o["prefab"].ToString() == "league"; bool isAdmin = o["tool"] != null && o["tool"]["usage"] != null && o["tool"]["usage"]["admin"] != null && o["tool"]["usage"]["admin"].ToString() == "1"; if (isLeague && !isAdmin) { var league = JsonConvert.DeserializeObject<DotaSchemaItem>(item.Value.ToString()); league.DefIndex = item.Name; leagues.Add(league); } } return leagues; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var token = JToken.Load(reader); if (token.Value<string>() != null) { var str = token.Value<string>(); switch (str) { case "CLASSIC": return GameMode.Classic; case "ODIN": return GameMode.Dominion; case "ARAM": return GameMode.Aram; case "TUTORIAL": return GameMode.Tutorial; case "ONEFORALL": return GameMode.OneForAll; case "FIRSTBLOOD": return GameMode.FirstBlood; case "any": return GameMode.Any; default: return null; } } return null; }
/// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader" /> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns> /// The object value. /// </returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject jobject = JObject.Load(reader); object target = null; if (jobject != null) { var keyType = jobject["key_type"].Value<string>(); if (string.Equals(keyType, SSHKeyType.otp.ToString(), StringComparison.OrdinalIgnoreCase)) { target = new SSHOTPRoleDefinition(); } else { if (string.Equals(keyType, SSHKeyType.dynamic.ToString(), StringComparison.OrdinalIgnoreCase)) { target = new SSHDynamicRoleDefinition(); } } } if (target != null) { serializer.Populate(jobject.CreateReader(), target); } return target; }
protected virtual object ReadJsonAsStringArray(JsonReader reader) { if (reader.TokenType != JsonToken.StartArray) { reader.Skip(); return null; } var rowValues = new List<string>(); var valueStartDepth = reader.Depth; var sb = new StringBuilder(); using (var sw = new StringWriter(sb)) { using (var jw = new JsonTextWriter(sw)) { while (reader.Read() && !(reader.TokenType == JsonToken.EndArray && reader.Depth == valueStartDepth)) { jw.WriteToken(reader, true); rowValues.Add(sb.ToString()); sb.Clear(); } } } return rowValues.ToArray(); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject jsonObject = JObject.Load(reader); string liteKey = (string)jsonObject["Key"]; return Lite.Parse(liteKey); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject o = JObject.Load(reader); var result = existingValue as Dictionary<string, TokenFilterBase> ?? new Dictionary<string, TokenFilterBase>(); foreach (var childProperty in o.Children<JProperty>()) { var propertyName = childProperty.Name; var typeProperty = ((JObject)childProperty.Value).Property("type"); typeProperty.Remove(); var typePropertyValue = typeProperty.Value.ToString().Replace("_", string.Empty); TokenFilterBase item; var itemType = Type.GetType("Nest." + typePropertyValue + "TokenFilter", false, true); if (itemType != null) { item = serializer.Deserialize(childProperty.Value.CreateReader(), itemType) as TokenFilterBase; } else { continue; } result[propertyName] = item; } return result; }
/// <summary> /// Creates a new object via the Factory. Loads the instance via the serializer. /// </summary> /// <param name="reader">The JsonReader</param> /// <param name="objectType">The Type of DTO</param> /// <param name="existingValue">The DTO</param> /// <param name="serializer">JsonSerializer</param> /// <returns></returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JsonReader objectReader = null; var instance = _container.CreateInstance(objectType); if (reader.TokenType == JsonToken.StartObject || reader.TokenType == JsonToken.StartArray) { if (reader.TokenType == JsonToken.StartObject) { var jObject = JObject.Load(reader); objectReader = jObject.CreateReader(); } if (reader.TokenType == JsonToken.StartArray) { var jArray = JArray.Load(reader); objectReader = jArray.CreateReader(); } if(objectReader != null) serializer.Populate(objectReader, instance); } return instance; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return null; } JObject globalStatsObject = JObject.Load(reader); List<GlobalStat> globalStats = new List<GlobalStat>(); foreach (var globalStatProperty in globalStatsObject.Children<JProperty>()) { GlobalStat globalStat = new GlobalStat(); globalStat.Name = globalStatProperty.Name; foreach (var globalStatDetailsProperty in globalStatProperty.Value.Children<JProperty>()) { string value = globalStatDetailsProperty.Value.ToString(); if (globalStatDetailsProperty.Name == "total") { globalStat.Total = Int32.Parse(value); } } globalStats.Add(globalStat); } return globalStats; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { ProductStatus productStatus; ProductStatus.TryParse(reader.Value.ToString(), true, out productStatus); return productStatus; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var obj = JObject.Load(reader); ProfitSharingStrategy strategy; var method = obj["Method"]; if (method == null) { throw new ArgumentNullException("Type", "Order type is null"); } var profitSharingMethod = (ProfitSharingMethod)Enum.Parse(typeof(ProfitSharingMethod), method.Value<string>()); switch (profitSharingMethod) { case ProfitSharingMethod.FLAT_RATE: strategy = new FlatRateStrategy(); break; case ProfitSharingMethod.PRICE_PERCENTAGE: strategy = new PricePercentageStrategy(); break; default: throw new NotImplementedException($"{profitSharingMethod.ToString()} is invalid/not supported"); } serializer.Populate(obj.CreateReader(), strategy); return strategy; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { List<ResolvedAction> resolvedActions = new List<ResolvedAction>(); JArray actionsArray = JArray.Load(reader); foreach (JObject jobject in actionsArray) { ResolvedAction resolvedAction = new ResolvedAction(); serializer.Populate(jobject.CreateReader(), resolvedAction); resolvedAction.BeaconAction = new BeaconAction(); serializer.Populate(jobject.CreateReader(), resolvedAction.BeaconAction); if (jobject["content"] != null) { serializer.Populate(jobject["content"]?.CreateReader(), resolvedAction.BeaconAction); resolvedAction.BeaconAction.PayloadString = jobject["content"]["payload"]?.ToString(); // create json object for fallback if(!string.IsNullOrEmpty(resolvedAction.BeaconAction.PayloadString)) { resolvedAction.BeaconAction.Payload = JsonObject.Parse(resolvedAction.BeaconAction.PayloadString); } } resolvedActions.Add(resolvedAction); } return resolvedActions; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } int result = 0; // What's happening in this code? We express [Flags] enums in JSON as arrays of // strings. On deserialization, we walk the array, locate each string, // and convert it to its equivalent enum value. Because we don't have a strong // sense of the destination type, we simply treat the enum values as numbers // and OR them together. This number will eventually be unboxed and assigned // to the target enum property. // Read start of array reader.Read(); while (reader.TokenType == JsonToken.String) { string enumName = EnumConverter.ConvertToPascalCase((string)reader.Value); result |= (int)Enum.Parse(objectType, enumName); reader.Read(); } return result; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (typeof(SecureString) == objectType) { return ((string)reader.Value).ToSecureString(); } return reader.Value; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var response = new GetWarmerResponse(); var warmersByIndex = JObject.Load(reader).Properties().ToDictionary(p => p.Name, p => p.Value); if (!warmersByIndex.HasAny()) return response; response.Indices = new Dictionary<string, Warmers>(); foreach (var warmerByIndex in warmersByIndex) { var index = warmerByIndex.Key; var warmersObject = JObject.FromObject(warmerByIndex.Value).Properties() .Where(p => p.Name == "warmers") .Select(p => p.Value) .FirstOrDefault(); var warmers = new Warmers(); if (warmersObject != null) { var warmersByName = JObject.FromObject(warmersObject).Properties() .ToDictionary(p => p.Name, p => p.Value); foreach (var warmerByName in warmersByName) { var name = warmerByName.Key; var warmer = warmerByName.Value.ToObject<Warmer>(); warmers.Add(name, warmer); } } response.Indices.Add(warmerByIndex.Key, warmers); } return response; }
/// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param><param name="objectType">Type of the object.</param><param name="existingValue">The existing value of object being read.</param><param name="serializer">The calling serializer.</param> /// <returns> /// The object value. /// </returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var coordinates = serializer.Deserialize<JArray>(reader); if (coordinates == null || coordinates.Count != 2) { throw new ParsingException( string.Format( "Point geometry coordinates could not be parsed. Expected something like '[-122.428938,37.766713]' ([lon,lat]), what we received however was: {0}", coordinates)); } string latitude; string longitude; try { longitude = coordinates.First.ToString(); latitude = coordinates.Last.ToString(); } catch (Exception ex) { throw new ParsingException("Could not parse GeoJSON Response. (Latitude or Longitude missing from Point geometry?)", ex); } return new List<IPosition> { new GeographicPosition(latitude, longitude) }; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var j = JObject.Load(reader); if (j == null || !j.HasValues) return null; IRegexpFilter filter = new RegexpFilterDescriptor<object>(); foreach (var jv in j) { switch (jv.Key) { case "_cache": filter.Cache = jv.Value.Value<bool>(); break; case "_cache_key": filter.CacheKey = jv.Value.Value<string>(); break; case "_name": filter.FilterName = jv.Value.Value<string>(); break; default: filter.Field = jv.Key; var value = jv.Value["value"]; if (value != null) filter.Value = value.Value<string>(); var flags = jv.Value["flags"]; if (flags != null) filter.Flags = flags.Value<string>(); break; } } return filter; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var s = reader.Value as string; if(s != null) { if (objectType == typeof(DateTime) || objectType == typeof(DateTime?)) { DateTime time; if (DateTime.TryParseExact(s, Default.DateTimeFormatsToRead, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out time)) { if (time.Kind == DateTimeKind.Unspecified) return DateTime.SpecifyKind(time, DateTimeKind.Local); return time; } } if(objectType == typeof(DateTimeOffset) || objectType == typeof(DateTimeOffset?)) { DateTimeOffset time; if (DateTimeOffset.TryParseExact(s, Default.DateTimeFormatsToRead, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out time)) return time; } } return DeferReadToNextConverter(reader, objectType, serializer, existingValue); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var obj = JToken.ReadFrom(reader); var ret = JsonConvert.DeserializeObject(obj.ToString(), ObjectType ?? objectType, new JsonConverter[] { }); if (obj["_embedded"] != null && obj["_embedded"].HasValues) { var enumerator = ((JObject) obj["_embedded"]).GetEnumerator(); while (enumerator.MoveNext()) { var rel = enumerator.Current.Key; foreach (var property in objectType.GetProperties()) { var attribute = property.GetCustomAttributes(true).FirstOrDefault(attr => attr is HalEmbeddedAttribute && ((HalEmbeddedAttribute) attr).Rel == rel); if (attribute != null) { var type = (attribute as HalEmbeddedAttribute).Type ?? property.PropertyType; property.SetValue(ret, JsonConvert.DeserializeObject(enumerator.Current.Value.ToString(), type, new JsonConverter[] {new HalResourceConverter((attribute as HalEmbeddedAttribute).CollectionMemberType)}), null); } } } } if (obj["_links"] != null && obj["_links"].HasValues && typeof (IHalResource).IsAssignableFrom(objectType)) { ((HalResource) ret).Links = JsonConvert.DeserializeObject<HalLinkCollection>(obj["_links"].ToString(), new JsonConverter[] {new HalLinkCollectionConverter()}); } if (ret is IHalResource) ((IHalResource) ret).IsNew = false; return ret; }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.ValueType == null) { var obj = JObject.Load(reader); Type type = null; var typeToken = obj["$type"]; if (typeToken != null) { string assemblyName = null; var typeName = typeToken.Value <string>(); var assemblyIndex = typeName.IndexOf(','); if (assemblyIndex > 0) { assemblyName = typeName.Substring(assemblyIndex + 1).Trim(); typeName = typeName.Substring(0, assemblyIndex); } type = serializer.Binder.BindToType(assemblyName, typeName); } else { type = objectType; } var target = Activator.CreateInstance(type); serializer.Populate(obj.CreateReader(), target); return(target); } if (objectType == reader.ValueType) { return(reader.Value); } var converter = GetConverter(objectType, reader.ValueType); if (converter != null) { return(converter.ConvertFrom(reader.Value)); } return(reader.Value); }
public override ObjectId ReadJson( JsonReader reader, Type objectType, ObjectId existingValue, bool hasExistingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.String) { var jsonLineInfo = (IJsonLineInfo)reader; throw new JsonSerializationException( $"Unexpected token parsing ObjectId. Expected String, got {reader.TokenType}.", reader.Path, jsonLineInfo.LineNumber, jsonLineInfo.LinePosition, null); } var sval = reader.Value?.ToString(); return(string.IsNullOrEmpty(sval) ? null : new ObjectId(sval)); }
public override object ReadJson(NewtonsoftJson.JsonReader reader, Type objectType, object existingValue, NewtonsoftJson.JsonSerializer serializer) { if (TYPE_INT64 == reader.ValueType) { if (objectType == TYPE_DATETIME || objectType == TYPE_NULLABLE_DATETIME) { return(DateTimeExtensions.TIMESTAMP_BASE.AddSeconds((long)reader.Value)); } else { return(reader.Value); } } else if (TYPE_DATETIME == reader.ValueType || TYPE_NULLABLE_DATETIME == reader.ValueType) { return(reader.Value); } else { return(null); } }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var obj = JToken.ReadFrom(reader); var id = (string)obj; var binder = serializer.Binder as EtoBinder; if (binder != null) { var instance = binder.Instance; if (instance != null) { var instanceType = instance.GetType(); var property = instanceType.GetRuntimeProperties().FirstOrDefault(r => r.Name == id); if (property != null) { return new Info { PropertyInfo = property, Instance = instance } } ; var field = instanceType.GetRuntimeFields().FirstOrDefault(r => r.Name == id); if (field != null) { return new Info { FieldInfo = field, Instance = instance } } ; } } return(null); }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { object instance; if (reader.TokenType == JsonToken.Null) { return(null); } if (reader.TokenType == JsonToken.String) { return(new StackLayoutItem { Control = Convert.ToString(reader.Value) }); } var container = JObject.Load(reader); if (container["$type"] == null) { instance = new StackLayoutItem(); serializer.Populate(container.CreateReader(), instance); } else { var type = Type.GetType((string)container["$type"]); if (!typeof(StackLayoutItem).IsAssignableFrom(type)) { var item = new StackLayoutItem(); item.Control = serializer.Deserialize(container.CreateReader()) as Control; instance = item; } else { instance = serializer.Deserialize(container.CreateReader()); } } return(instance); }
/// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">Existing Value</param> /// <param name="serializer">Serializer</param> /// <returns>The object value.</returns> public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null && objectType.IsAssignableFrom(typeof(DateTime?))) { return(null); } if (reader.TokenType == JsonToken.Date) { return((DateTime)reader.Value); } if (reader.TokenType != JsonToken.String) { throw new Exception("Unexpected token parsing date. Expected String, got {0}.".FormatWith(reader.TokenType)); } if (reader.Value.ToString().IsEmpty()) { return(null); } return(DateTime.Parse(reader.Value.ToString(), CultureInfo.InvariantCulture)); }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { JObject obj = serializer.Deserialize <JToken>(reader) as JObject; if (obj != null) { string result = obj["isSingleUnit"].ToObject <string>(); bool isSingleUnit = ConvertToBool(result); string name = obj["name"].ToObject <string>(); if (isSingleUnit) { return(new NewtonTest.House(name, isSingleUnit)); } else { return(new NewtonTest.Apartment(name, isSingleUnit)); } } else { return(null); } }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { JObject jObject = null; jObject = serializer.Deserialize <Newtonsoft.Json.Linq.JObject>(reader); if (jObject == null) { return(null); } var discriminator = Newtonsoft.Json.Linq.Extensions.Value <string>(jObject.GetValue(_discriminator)); var subtype = GetObjectSubtypeBetter(jObject, objectType, discriminator); try { _isReading = true; return(serializer.Deserialize(jObject.CreateReader(), subtype)); } finally { _isReading = false; } }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { //If you need to deserialize, fill in the code here return(null); }
private void tvPdfDoc_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { if (e.Node.Tag == null || key_ == 0) { return; } txtStream.Text = string.Empty; var idxObj = e.Node.Tag as ObjInfo; var idx = -1; if (idxObj != null && idxObj.idx_ >= 0) { idx = idxObj.idx_; } else if (chkRefResolve.Checked && idxObj.pdfObj_ != null && idxObj.pdfObj_.ContainsKey("$Type") && idxObj.refresolve_ == false) { // resolve obj ref; var objnum = Convert.ToInt32(idxObj.pdfObj_["num"]); idxObj.idx_ = objnum; var len = PdfAnal.analObject(key_, objnum); var buff = new byte[len]; //new StringBuilder((int)len); PdfAnal.getBuff(key_, buff); var docstr = Encoding.UTF8.GetString(buff); var jsr = new Newtonsoft.Json.JsonReader(new StringReader(docstr)); var js = new Newtonsoft.Json.JsonSerializer(); var jsroot = js.Deserialize(jsr); e.Node.Nodes.Clear(); jsoFunc(jsroot, "", null, e.Node, false, 10); // 10は適当 e.Node.Text = string.Format("{0} ({1} 0 R)", e.Node.Text, objnum); } else { return; } var stmlen = PdfAnal.analObjStream(key_, idx); if (stmlen == 0) { return; } var stmbuf = new byte[stmlen]; PdfAnal.getBuff(key_, stmbuf); var tmpPath = Path.Combine(Path.GetTempPath(), "pdfanl.tmp"); using (var tmp = new FileStream(tmpPath, FileMode.Create, FileAccess.Write)) { tmp.Write(stmbuf, 0, stmbuf.Length); } using (var tmp = new StreamReader(tmpPath)) { var txtBuf = new StringBuilder(); while (true) { var line = tmp.ReadLine(); if (line == null || txtBuf.Length > (2 << 15)) { break; } txtBuf.AppendLine(line); } txtStream.Text = txtBuf.ToString(); } }
/// <summary> /// Reads the json. /// </summary> /// <param name="reader">The reader.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value.</param> /// <param name="serializer">The serializer.</param><returns></returns> public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { JObject jObject = JObject.Load(reader); DataTable table = new DataTable(); if (jObject["TableName"] != null) { table.TableName = jObject["TableName"].ToString(); } if (jObject["Columns"] == null) { return(table); } // Loop through the columns in the table and apply any properties provided foreach (JObject jColumn in jObject["Columns"]) { DataColumn column = new DataColumn(); JToken token = default(JToken); token = jColumn.SelectToken("AllowDBNull"); if (token != null) { column.AllowDBNull = token.Value <bool>(); } token = jColumn.SelectToken("AutoIncrement"); if (token != null) { column.AutoIncrement = token.Value <bool>(); } token = jColumn.SelectToken("AutoIncrementSeed"); if (token != null) { column.AutoIncrementSeed = token.Value <long>(); } token = jColumn.SelectToken("AutoIncrementStep"); if (token != null) { column.AutoIncrementStep = token.Value <long>(); } token = jColumn.SelectToken("Caption"); if (token != null) { column.Caption = token.Value <string>(); } token = jColumn.SelectToken("ColumnName"); if (token != null) { column.ColumnName = token.Value <string>(); } // Allowed data types: http://msdn.microsoft.com/en-us/library/system.data.datacolumn.datatype.aspx token = jColumn.SelectToken("DataType"); if (token != null) { string dataType = token.Value <string>(); if (dataType == "Byte[]") { column.DataType = typeof(System.Byte[]); } else { // All allowed data types exist in the System namespace column.DataType = Type.GetType(string.Concat("System.", dataType)); } } token = jColumn.SelectToken("DateTimeMode"); if (token != null) { column.DateTimeMode = (System.Data.DataSetDateTime)Enum.Parse(typeof(System.Data.DataSetDateTime), token.Value <string>()); } // Can't set default value on auto increment column if (!column.AutoIncrement) { token = jColumn.SelectToken("DefaultValue"); if (token != null) { column.DefaultValue = this.ConvertFromString(column.DataType, token.ToString()); } } token = jColumn.SelectToken("MaxLength"); if (token != null) { column.MaxLength = token.Value <int>(); } token = jColumn.SelectToken("ReadOnly"); if (token != null) { column.ReadOnly = token.Value <bool>(); } token = jColumn.SelectToken("Unique"); if (token != null) { column.Unique = token.Value <bool>(); } table.Columns.Add(column); } // Add the rows to the table if (jObject["Rows"] != null) { foreach (JArray jRow in jObject["Rows"]) { DataRow row = table.NewRow(); // Each row is just an array of objects row.ItemArray = jRow.ToObject <System.Object[]>(); table.Rows.Add(row); } } // Add the primary key to the table if supplied if (jObject["PrimaryKey"] != null) { List <DataColumn> primaryKey = new List <DataColumn>(); foreach (JValue jPrimaryKey in jObject["PrimaryKey"]) { DataColumn column = table.Columns[jPrimaryKey.ToString()]; if (column == null) { throw new ApplicationException("Invalid primary key."); } else { primaryKey.Add(column); } } table.PrimaryKey = primaryKey.ToArray(); } return(table); }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { object instance; JContainer container; if (reader.TokenType == JsonToken.Null) { return(null); } if (reader.TokenType == JsonToken.StartArray) { container = JArray.Load(reader); if (objectType == typeof(DynamicRow)) { var dynamicRow = new DynamicRow(); instance = dynamicRow; serializer.Populate(container.CreateReader(), dynamicRow.Items); } else if (objectType == typeof(DynamicItem)) { var dynamicTable = new DynamicTable(); instance = dynamicTable; serializer.Populate(container.CreateReader(), dynamicTable.Rows); } else { throw new EtoException("Invalid object graph"); } } else { container = JObject.Load(reader); if (container["$type"] == null) { if (container["Rows"] != null) { instance = new DynamicTable(); } else if (container["Control"] != null) { instance = new DynamicControl(); } else { throw new EtoException("Could not infer the type of object to create"); } serializer.Populate(container.CreateReader(), instance); } else { var type = Type.GetType((string)container ["$type"]); if (!typeof(DynamicItem).IsAssignableFrom(type)) { var dynamicControl = new DynamicControl(); dynamicControl.Control = serializer.Deserialize(container.CreateReader()) as Control; instance = dynamicControl; } else { instance = serializer.Deserialize(container.CreateReader()); } } } if (objectType == typeof(DynamicRow) && instance.GetType() != typeof(DynamicRow)) { var row = new DynamicRow(); row.Items.Add(instance as DynamicItem); return(row); } return(instance); }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return(Enum.Parse(objectType, reader.Value.ToString(), true)); }
private void DeserializeNode(Newtonsoft.Json.JsonReader reader, XmlDocument document, XmlNamespaceManager manager, XmlNode currentNode) { if (currentNode.NodeType == XmlNodeType.Document) { XmlElement root = document.CreateElement("records"); document.AppendChild(root); currentNode = root; } XmlNode savedNode = currentNode; do { if (savedNode.Name == "records" && savedNode.ParentNode.NodeType == XmlNodeType.Document) { currentNode = savedNode; } switch (reader.TokenType) { case JsonToken.PropertyName: if (currentNode.NodeType == XmlNodeType.Document && document.DocumentElement != null) { throw new JsonSerializationException("JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document."); } string propertyName = reader.Value.ToString(); reader.Read(); if (reader.TokenType == JsonToken.StartArray) { while (reader.Read() && reader.TokenType != JsonToken.EndArray) { if (reader.TokenType == JsonToken.StartObject) { if (currentNode.Name == "records" && currentNode.ParentNode.NodeType == XmlNodeType.Document && (propertyName == "Updated" || propertyName == "Created" || propertyName == "Deleted")) { XmlNode tempNode = currentNode.SelectSingleNode(propertyName); if (tempNode != null) { currentNode = tempNode; propertyName = "record"; } } } DeserializeValue(reader, document, manager, propertyName, currentNode); } } else { bool addRecord = currentNode.ParentNode != null && currentNode.ParentNode.ParentNode != null && currentNode.ParentNode.Name == "records" && currentNode.ParentNode.ParentNode.NodeType == XmlNodeType.Document; if ((currentNode.Name == "Updated" || currentNode.Name == "Created" || currentNode.Name == "Deleted") && addRecord) { XmlElement record = document.CreateElement("record"); currentNode.AppendChild(record); currentNode = record; } DeserializeValue(reader, document, manager, propertyName, currentNode); } break; case JsonToken.StartConstructor: string constructorName = reader.Value.ToString(); while (reader.Read() && reader.TokenType != JsonToken.EndConstructor) { DeserializeValue(reader, document, manager, "-" + constructorName, currentNode); } break; case JsonToken.EndObject: case JsonToken.EndArray: return; default: throw new JsonSerializationException("Unexpected JsonToken when deserializing node: " + reader.TokenType); } } while (reader.TokenType == JsonToken.PropertyName || reader.Read()); // don't read if current token is a property. token was already read when parsing element attributes }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { var jToken = serializer.Deserialize <JToken>(reader); return(ConvertJToken(jToken, keepPrimitiveValues: false)); }
/// <summary> /// Reads the json. /// </summary> /// <param name="reader">The reader.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value.</param> /// <param name="serializer">The serializer.</param><returns></returns> public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { JObject jObject = JObject.Load(reader); DataTable table = new DataTable(); if (jObject["TableName"] != null) { table.TableName = jObject["TableName"].ToString(); } if (jObject["Columns"] == null) { return(table); } // Loop through the columns in the table and apply any properties provided foreach (JObject jColumn in jObject["Columns"]) { DataColumn column = new DataColumn(); JToken token = default(JToken); token = jColumn.SelectToken("AllowDBNull"); if (token != null) { column.AllowDBNull = token.Value <bool>(); } token = jColumn.SelectToken("AutoIncrement"); if (token != null) { column.AutoIncrement = token.Value <bool>(); } token = jColumn.SelectToken("AutoIncrementSeed"); if (token != null) { column.AutoIncrementSeed = token.Value <long>(); } token = jColumn.SelectToken("AutoIncrementStep"); if (token != null) { column.AutoIncrementStep = token.Value <long>(); } token = jColumn.SelectToken("Caption"); if (token != null) { column.Caption = token.Value <string>(); } token = jColumn.SelectToken("ColumnName"); if (token != null) { column.ColumnName = token.Value <string>(); } // Allowed data types: http://msdn.microsoft.com/en-us/library/system.data.datacolumn.datatype.aspx token = jColumn.SelectToken("DataType"); if (token != null) { string dataType = token.Value <string>(); if (dataType == "Byte[]") { column.DataType = typeof(System.Byte[]); } else { // All allowed data types exist in the System namespace column.DataType = Type.GetType(string.Concat("System.", dataType)); } } token = jColumn.SelectToken("DateTimeMode"); if (token != null) { column.DateTimeMode = (DataSetDateTime)Enum.Parse(typeof(System.Data.DataSetDateTime), token.Value <string>()); } // Can't set default value on auto increment column if (!column.AutoIncrement) { token = jColumn.SelectToken("DefaultValue"); if (token != null) { // If a default value is provided then cast to the columns data type switch (column.DataType.Name) { case "Boolean": bool defaultValueBool = false; if (bool.TryParse(token.ToString(), out defaultValueBool)) { column.DefaultValue = defaultValueBool; } break; case "Byte": byte defaultValueByte = 0; if (byte.TryParse(token.ToString(), out defaultValueByte)) { column.DefaultValue = defaultValueByte; } break; case "Char": char defaultValueChar = '\0'; if (char.TryParse(token.ToString(), out defaultValueChar)) { column.DefaultValue = defaultValueChar; } break; case "DateTime": DateTime defaultValueDateTime = default(DateTime); if (DateTime.TryParse(token.ToString(), out defaultValueDateTime)) { column.DefaultValue = defaultValueDateTime; } break; case "Decimal": decimal defaultValueDeciumal = default(decimal); if (decimal.TryParse(token.ToString(), out defaultValueDeciumal)) { column.DefaultValue = defaultValueDeciumal; } break; case "Double": double defaultValueDouble = 0; if (double.TryParse(token.ToString(), out defaultValueDouble)) { column.DefaultValue = defaultValueDouble; } break; case "Guid": Guid defaultValueGuid = default(Guid); if (Guid.TryParse(token.ToString(), out defaultValueGuid)) { column.DefaultValue = defaultValueGuid; } break; case "Int16": Int16 defaultValueInt16 = default(Int16); if (Int16.TryParse(token.ToString(), out defaultValueInt16)) { column.DefaultValue = defaultValueInt16; } break; case "Int32": Int32 defaultValueInt32 = default(Int32); if (Int32.TryParse(token.ToString(), out defaultValueInt32)) { column.DefaultValue = defaultValueInt32; } break; case "Int64": Int64 defaultValueInt64 = default(Int64); if (Int64.TryParse(token.ToString(), out defaultValueInt64)) { column.DefaultValue = defaultValueInt64; } break; case "SByte": sbyte defaultValueSByte = 0; if (sbyte.TryParse(token.ToString(), out defaultValueSByte)) { column.DefaultValue = defaultValueSByte; } break; case "Single": float defaultValueSingle = 0; if (float.TryParse(token.ToString(), out defaultValueSingle)) { column.DefaultValue = defaultValueSingle; } break; case "String": column.DefaultValue = token.ToString(); break; case "TimeSpan": TimeSpan defaultValueTimeSpan = default(TimeSpan); if (TimeSpan.TryParse(token.ToString(), out defaultValueTimeSpan)) { column.DefaultValue = defaultValueTimeSpan; } break; case "UInt16": UInt16 defaultValueUInt16 = default(UInt16); if (UInt16.TryParse(token.ToString(), out defaultValueUInt16)) { column.DefaultValue = defaultValueUInt16; } break; case "UInt32": UInt32 defaultValueUInt32 = default(UInt32); if (UInt32.TryParse(token.ToString(), out defaultValueUInt32)) { column.DefaultValue = defaultValueUInt32; } break; case "UInt64": UInt64 defaultValueUInt64 = default(UInt64); if (UInt64.TryParse(token.ToString(), out defaultValueUInt64)) { column.DefaultValue = defaultValueUInt64; } break; case "Byte[]": break; // Leave as null } } } token = jColumn.SelectToken("MaxLength"); if (token != null) { column.MaxLength = token.Value <int>(); } token = jColumn.SelectToken("ReadOnly"); if (token != null) { column.ReadOnly = token.Value <bool>(); } token = jColumn.SelectToken("Unique"); if (token != null) { column.Unique = token.Value <bool>(); } table.Columns.Add(column); } // Add the rows to the table if (jObject["Rows"] != null) { foreach (JArray jRow in jObject["Rows"]) { DataRow row = table.NewRow(); // Each row is just an array of objects row.ItemArray = jRow.ToObject <System.Object[]>(); table.Rows.Add(row); } } // Add the primary key to the table if supplied if (jObject["PrimaryKey"] != null) { List <DataColumn> primaryKey = new List <DataColumn>(); foreach (JValue jPrimaryKey in jObject["PrimaryKey"]) { DataColumn column = table.Columns[jPrimaryKey.ToString()]; if (column == null) { throw new ApplicationException("Invalid primary key."); } else { primaryKey.Add(column); } } table.PrimaryKey = primaryKey.ToArray(); } return(table); }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return(PaperSize.GetPaperSize(reader.Value as string)); }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { return(DateTime.Parse(reader.Value.ToString())); }
public static JsonNewtonsoftReader Create(Newtonsoft.Json.JsonReader reader) { return(new JsonNewtonsoftReader(reader)); }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { object instance; JContainer container; if (reader.TokenType == JsonToken.Null) { return(null); } if (reader.TokenType == JsonToken.String) { if (objectType == typeof(TableRow)) { return(new TableRow(Convert.ToString(reader.Value))); } if (objectType == typeof(TableCell)) { return(new TableCell(Convert.ToString(reader.Value))); } } if (reader.TokenType == JsonToken.StartArray) { container = JArray.Load(reader); if (objectType == typeof(TableRow)) { var row = new TableRow(); instance = row; serializer.Populate(container.CreateReader(), row.Cells); } else if (objectType == typeof(TableCell)) { var table = new TableLayout(); serializer.Populate(container.CreateReader(), table.Rows); instance = new TableCell(table); } else { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid object graph")); } } else { container = JObject.Load(reader); if (container["$type"] == null) { if (container["Rows"] != null) { instance = new TableLayout(); } else if (container["Cells"] != null) { instance = new TableRow(); } else if (container["Control"] != null) { instance = new TableCell(); } else if (objectType == typeof(TableRow)) { instance = new TableRow(); } else if (objectType == typeof(TableCell)) { instance = new TableCell(); } else { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Could not infer the type of object to create")); } serializer.Populate(container.CreateReader(), instance); } else { var type = Type.GetType((string)container["$type"]); if (!typeof(TableCell).IsAssignableFrom(type)) { var cell = new TableCell(); cell.Control = serializer.Deserialize(container.CreateReader()) as Control; instance = cell; } else { instance = serializer.Deserialize(container.CreateReader()); } } } if (objectType == typeof(TableRow) && !(instance is TableRow)) { var row = new TableRow(); var cell = instance as TableCell; if (cell == null) { cell = new TableCell(instance as Control); } row.Cells.Add(cell); return(row); } return(instance); }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { return(DateTime.ParseExact((string)reader.Value, "MM/yyyy", CultureInfo.InvariantCulture)); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var data = reader.ReadAsString(); return(data.ToColor()); }
private void DeserializeValue(Newtonsoft.Json.JsonReader reader, XmlDocument document, XmlNamespaceManager manager, string propertyName, XmlNode currentNode) { // deserialize xml element bool finishedAttributes = false; bool finishedElement = false; Dictionary <string, string> attributeNameValues = new Dictionary <string, string>(); // a string token means the element only has a single text child if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null && reader.TokenType != JsonToken.Boolean && reader.TokenType != JsonToken.Integer && reader.TokenType != JsonToken.Float && reader.TokenType != JsonToken.Date && reader.TokenType != JsonToken.StartConstructor) { // read properties until first non-attribute is encountered while (!finishedAttributes && !finishedElement && reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: string attributeName = reader.Value.ToString(); if (attributeName[0] == '@') { attributeName = attributeName.Substring(1); reader.Read(); string attributeValue = reader.Value.ToString(); attributeNameValues.Add(attributeName, attributeValue); } else { finishedAttributes = true; } break; case JsonToken.EndObject: finishedElement = true; break; default: throw new JsonSerializationException("Unexpected JsonToken: " + reader.TokenType); } } } // have to wait until attributes have been parsed before creating element // attributes may contain namespace info used by the element XmlElement element = document.CreateElement(propertyName); currentNode.AppendChild(element); // add attributes to newly created element foreach (KeyValuePair <string, string> nameValue in attributeNameValues) { XmlAttribute attribute = document.CreateAttribute(nameValue.Key); attribute.Value = nameValue.Value; element.SetAttributeNode(attribute); } if (reader.TokenType == JsonToken.String) { element.AppendChild(document.CreateTextNode(reader.Value.ToString())); } else if (reader.TokenType == JsonToken.Integer) { element.AppendChild(document.CreateTextNode(XmlConvert.ToString((long)reader.Value))); } else if (reader.TokenType == JsonToken.Float) { element.AppendChild(document.CreateTextNode(XmlConvert.ToString((double)reader.Value))); } else if (reader.TokenType == JsonToken.Boolean) { element.AppendChild(document.CreateTextNode(XmlConvert.ToString((bool)reader.Value))); } else if (reader.TokenType == JsonToken.Date) { DateTime d = (DateTime)reader.Value; element.AppendChild(document.CreateTextNode(XmlConvert.ToString(d, ToSerializationMode(d.Kind)))); } else if (reader.TokenType == JsonToken.Null) { // empty element. do nothing } else { // finished element will have no children to deserialize if (!finishedElement) { manager.PushScope(); DeserializeNode(reader, document, manager, element); manager.PopScope(); } } }
/// <inheritdoc/> public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException("Unnecessary because CanRead is false."); }
/// <summary> /// Reads the json. /// </summary> /// <param name="reader">The reader.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value.</param> /// <param name="serializer">The serializer.</param><returns></returns> public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { JObject jObject = JObject.Load(reader); DataTable table = new DataTable(); if (jObject["TableName"] != null) { table.TableName = jObject["TableName"].ToString(); } if (jObject["Columns"] == null) { return(table); } // Loop through the columns in the table and apply any properties provided foreach (JObject jColumn in jObject["Columns"]) { DataColumn column = new DataColumn(); JToken token = default(JToken); token = jColumn.SelectToken("AllowDBNull"); if (token != null) { column.AllowDBNull = token.Value <bool>(); } token = jColumn.SelectToken("AutoIncrement"); if (token != null) { column.AutoIncrement = token.Value <bool>(); } token = jColumn.SelectToken("AutoIncrementSeed"); if (token != null) { column.AutoIncrementSeed = token.Value <long>(); } token = jColumn.SelectToken("AutoIncrementStep"); if (token != null) { column.AutoIncrementStep = token.Value <long>(); } token = jColumn.SelectToken("Caption"); if (token != null) { column.Caption = token.Value <string>(); } token = jColumn.SelectToken("ColumnName"); if (token != null) { column.ColumnName = token.Value <string>(); } // Allowed data types: http://msdn.microsoft.com/en-us/library/system.data.datacolumn.datatype.aspx token = jColumn.SelectToken("DataType"); if (token != null) { string dataType = token.Value <string>(); if (dataType == "Byte[]") { column.DataType = typeof(System.Byte[]); } else { // All allowed data types exist in the System namespace column.DataType = System.Type.GetType(string.Concat("System.", dataType)); } } token = jColumn.SelectToken("DateTimeMode"); if (token != null) { DataSetDateTime dtm; Enum.TryParse <DataSetDateTime>(token.Value <string>(), out dtm); column.DateTimeMode = dtm; } // Can't set default value on auto increment column if (!column.AutoIncrement) { token = jColumn.SelectToken("DefaultValue"); if (token != null) { // If a default value is provided then cast to the columns data type if (column.DataType == typeof(System.Boolean)) { bool defaultValue = false; if (bool.TryParse(token.ToString(), out defaultValue)) { column.DefaultValue = defaultValue; } } else { if (column.DataType == typeof(System.Byte)) { byte defaultValue = 0; if (byte.TryParse(token.ToString(), out defaultValue)) { column.DefaultValue = defaultValue; } } else { /* * case typeof(System.Char): * char defaultValue = '\0'; * if (char.TryParse(token.ToString(), out defaultValue)) * { * column.DefaultValue = defaultValue; * } * break; * case typeof(System.DateTime): * DateTime defaultValue = default(DateTime); * if (DateTime.TryParse(token.ToString(), out defaultValue)) * { * column.DefaultValue = defaultValue; * } * break; * case typeof(System.Decimal): * decimal defaultValue = default(decimal); * if (decimal.TryParse(token.ToString(), out defaultValue)) * { * column.DefaultValue = defaultValue; * } * break; * case typeof(System.Double): * double defaultValue = 0; * if (double.TryParse(token.ToString(), out defaultValue)) * { * column.DefaultValue = defaultValue; * } * break; * case typeof(System.Guid): * Guid defaultValue = default(Guid); * if (Guid.TryParse(token.ToString(), out defaultValue)) * { * column.DefaultValue = defaultValue; * } * break; * case typeof(System.Int16): * Int16 defaultValue = default(Int16); * if (Int16.TryParse(token.ToString(), out defaultValue)) * { * column.DefaultValue = defaultValue; * } * break; * case typeof(System.Int32): * Int32 defaultValue = default(Int32); * if (Int32.TryParse(token.ToString(), out defaultValue)) * { * column.DefaultValue = defaultValue; * } * break; * case typeof(System.Int64): * Int64 defaultValue = default(Int64); * if (Int64.TryParse(token.ToString(), out defaultValue)) * { * column.DefaultValue = defaultValue; * } * break; * case typeof(System.SByte): * sbyte defaultValue = 0; * if (sbyte.TryParse(token.ToString(), out defaultValue)) * { * column.DefaultValue = defaultValue; * } * break; * case typeof(System.Single): * float defaultValue = 0; * if (float.TryParse(token.ToString(), out defaultValue)) * { * column.DefaultValue = defaultValue; * } * break; * case typeof(System.String): * column.DefaultValue = token.ToString(); * break; * case typeof(System.TimeSpan): * TimeSpan defaultValue = default(TimeSpan); * if (TimeSpan.TryParse(token.ToString(), out defaultValue)) * { * column.DefaultValue = defaultValue; * } * break; * case typeof(System.UInt16): * UInt16 defaultValue = default(UInt16); * if (UInt16.TryParse(token.ToString(), out defaultValue)) * { * column.DefaultValue = defaultValue; * } * break; * case typeof(System.UInt32): * UInt32 defaultValue = default(UInt32); * if (UInt32.TryParse(token.ToString(), out defaultValue)) * { * column.DefaultValue = defaultValue; * } * break; * case typeof(System.UInt64): * UInt64 defaultValue = default(UInt64); * if (UInt64.TryParse(token.ToString(), out defaultValue)) * { * column.DefaultValue = defaultValue; * } * break; * case typeof(System.Byte[]): * break; * // Leave as null */ } } } } token = jColumn.SelectToken("MaxLength"); if (token != null) { column.MaxLength = token.Value <int>(); } token = jColumn.SelectToken("ReadOnly"); if (token != null) { column.ReadOnly = token.Value <bool>(); } token = jColumn.SelectToken("Unique"); if (token != null) { column.Unique = token.Value <bool>(); } table.Columns.Add(column); } // Add the rows to the table if (jObject["Rows"] != null) { foreach (JArray jRow in jObject["Rows"]) { DataRow row = table.NewRow(); // Each row is just an array of objects row.ItemArray = jRow.ToObject <System.Object[]>(); table.Rows.Add(row); } } // Add the primary key to the table if supplied if (jObject["PrimaryKey"] != null) { List <DataColumn> primaryKey = new List <DataColumn>(); foreach (JValue jPrimaryKey in jObject["PrimaryKey"]) { DataColumn column = table.Columns[jPrimaryKey.ToString()]; if (column == null) { throw new ApplicationException("Invalid primary key."); } else { primaryKey.Add(column); } } table.PrimaryKey = primaryKey.ToArray(); } return(table); }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { return(serializer.Deserialize(reader, typeof(IDictionary <string, object>))); }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { if (reader.TokenType == Newtonsoft.Json.JsonToken.Null) { return(null); } try { var token = (JObject)JToken.Load(reader); var isCamelCased = true; WalkNode(token, null, t => { var nameFirstChar = t.Name[0].ToString(); if (!nameFirstChar.Equals(nameFirstChar.ToLower(), StringComparison.CurrentCulture)) { isCamelCased = false; return; } }); if (!isCamelCased) { return(null); } return(token.ToObject(objectType)); } catch (System.Exception) { } try { var token = (JArray)JToken.Load(reader); var isCamelCased = true; WalkNode(token, null, t => { var nameFirstChar = t.Name[0].ToString(); if (!nameFirstChar.Equals(nameFirstChar.ToLower(), StringComparison.CurrentCulture)) { isCamelCased = false; return; } }); if (!isCamelCased) { return(null); } return(token.ToObject(objectType)); } catch (System.Exception) { } return(null); }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return(new ObjectId((string)reader.Value)); }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); }
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType) { throw new NotImplementedException(); }