本文整理汇总了C#中JsonConverter类的典型用法代码示例。如果您正苦于以下问题:C# JsonConverter类的具体用法?C# JsonConverter怎么用?C# JsonConverter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
JsonConverter类属于命名空间,在下文中一共展示了JsonConverter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SerializeVector3
/// <summary>
/// Simple Vector3 Serialization
/// </summary>
public void SerializeVector3()
{
LogStart("Vector3 Serialization");
try
{
var v = new Vector3(2, 4, 6);
var converters = new JsonConverter[]
{
new Vector3Converter()
};
var serialized = JsonConvert.SerializeObject(v, Formatting.None, converters);
LogSerialized(serialized);
var v2 = JsonConvert.DeserializeObject<Vector3>(serialized);
LogResult("4", v2.y);
if (v2.y != v.y)
{
DisplayFail("Vector3 Serialization", BAD_RESULT_MESSAGE);
}
DisplaySuccess("Vector3 Serialization");
}
catch(Exception ex)
{
DisplayFail("Vector3 Serialization", ex.Message);
}
LogEnd(1);
}
示例2: MainPage
public MainPage()
{
InitializeComponent();
isoSettings = IsolatedStorageSettings.ApplicationSettings;
basicJsonObjectConverter = new JsonConverter<BasicJsonObject>();
// TODO Remove
App.Settings.APP_ID = "cylinder-manager-e30";
App.Settings.API_KEY = "d6c6b4b7aa0f4162a04f23ebd34c6d2e";
App.Settings.ADMIN_KEY = "e4b4709e31924777a4521df5fbf57692";
data = new BasicJsonObject();
// use two-way binding to set BasicjsonObject's key/value pairs
JsonObjectGrid.DataContext = data;
if (isoSettings.Contains(SETTINGS_BUCKET_NAME))
BucketName_Box.Text = isoSettings[SETTINGS_BUCKET_NAME] as string;
if (isoSettings.Contains(SETTINGS_OBJECT_ID))
ObjectId_Box.Text = isoSettings[SETTINGS_OBJECT_ID] as string;
if (isoSettings.Contains(SETTINGS_CCID))
CCID_Box.Text = isoSettings[SETTINGS_CCID] as string;
if (isoSettings.Contains(SETTINGS_CLIENT_ID))
ClientId_Box.Text = isoSettings[SETTINGS_CLIENT_ID] as string;
}
示例3: TryConvertingFromStreamEmptyToSimpleObject
public void TryConvertingFromStreamEmptyToSimpleObject()
{
using (Stream stream = examples.EmptyObject())
{
JsonConverter<ObjectWithName> converter = new JsonConverter<ObjectWithName>();
ObjectWithName objectExpected = converter.ConvertFrom(stream);
}
}
示例4: TryConvertingFromJsonToSimpleObject
public void TryConvertingFromJsonToSimpleObject()
{
using (Stream stream = examples.JsonStream())
{
JsonConverter<ObjectWithName> converter = new JsonConverter<ObjectWithName>();
ObjectWithName objectPopulated = converter.ConvertFrom(stream);
Assert.IsTrue(objectPopulated.Name == Constants.MockObjectValue);
}
}
示例5: TryConvertingFromEmptyValidObjectToSimpleObject
public void TryConvertingFromEmptyValidObjectToSimpleObject()
{
using (Stream stream = examples.EmptyValidObject())
{
JsonConverter<ObjectWithName> converter = new JsonConverter<ObjectWithName>();
ObjectWithName objectExpected = converter.ConvertFrom(stream);
Assert.IsTrue(objectExpected.Name == new ObjectWithName().Name);
}
}
示例6: SerializeValue
private void SerializeValue(JsonWriter writer, object value, JsonConverter memberConverter)
{
JsonConverter converter = memberConverter;
if (value == null)
{
writer.WriteNull();
}
else if (converter != null
|| _serializer.HasClassConverter(value.GetType(), out converter)
|| _serializer.HasMatchingConverter(value.GetType(), out converter))
{
SerializeConvertable(writer, converter, value);
}
else if (JsonConvert.IsJsonPrimitive(value))
{
writer.WriteValue(value);
}
else if (value is JToken)
{
((JToken)value).WriteTo(writer, (_serializer.Converters != null) ? _serializer.Converters.ToArray() : null);
}
else if (value is JsonRaw)
{
writer.WriteRawValue(((JsonRaw)value).Content);
}
else
{
JsonContract contract = _serializer.ContractResolver.ResolveContract(value.GetType());
if (contract is JsonObjectContract)
{
SerializeObject(writer, value, (JsonObjectContract)contract);
}
else if (contract is JsonDictionaryContract)
{
SerializeDictionary(writer, (IDictionary)value, (JsonDictionaryContract)contract);
}
else if (contract is JsonArrayContract)
{
if (value is IList)
{
SerializeList(writer, (IList)value, (JsonArrayContract)contract);
}
else if (value is IEnumerable)
{
SerializeEnumerable(writer, (IEnumerable)value, (JsonArrayContract)contract);
}
else
{
throw new Exception("Cannot serialize '{0}' into a JSON array. Type does not implement IEnumerable.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
}
}
}
示例7: JsonMemberMapping
public JsonMemberMapping(string mappingName, MemberInfo member, bool ignored, bool readable, bool writable, JsonConverter memberConverter, object defaultValue, bool required)
{
_mappingName = mappingName;
_member = member;
_ignored = ignored;
_readable = readable;
_writable = writable;
_memberConverter = memberConverter;
_defaultValue = defaultValue;
_required = required;
}
示例8: SetPropertyValue
// Token: 0x06000BC8 RID: 3016
// RVA: 0x00044828 File Offset: 0x00042A28
private bool SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target)
{
bool flag;
object value;
JsonContract contract;
bool flag2;
if (this.CalculatePropertyDetails(property, ref propertyConverter, containerContract, containerProperty, reader, target, out flag, out value, out contract, out flag2))
{
return false;
}
object obj;
if (propertyConverter != null && propertyConverter.CanRead)
{
if (!flag2 && target != null && property.Readable)
{
value = property.ValueProvider.GetValue(target);
}
obj = this.DeserializeConvertable(propertyConverter, reader, property.PropertyType, value);
}
else
{
obj = this.CreateValueInternal(reader, property.PropertyType, contract, property, containerContract, containerProperty, flag ? value : null);
}
if ((!flag || obj != value) && this.ShouldSetPropertyValue(property, obj))
{
property.ValueProvider.SetValue(target, obj);
if (property.SetIsSpecified != null)
{
if (this.TraceWriter != null && this.TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
this.TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, StringUtils.FormatWith("IsSpecified for property '{0}' on {1} set to true.", CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType)), null);
}
property.SetIsSpecified(target, true);
}
return true;
}
return flag;
}
示例9: GetConverter
private JsonConverter GetConverter(JsonContract contract, JsonConverter memberConverter)
{
JsonConverter converter = null;
if (memberConverter != null)
{
// member attribute converter
converter = memberConverter;
}
else if (contract != null)
{
JsonConverter matchingConverter;
if (contract.Converter != null)
// class attribute converter
converter = contract.Converter;
else if ((matchingConverter = Serializer.GetMatchingConverter(contract.UnderlyingType)) != null)
// passed in converters
converter = matchingConverter;
else if (contract.InternalConverter != null)
// internally specified converter
converter = contract.InternalConverter;
}
return converter;
}
示例10: CreateValueProperty
private object CreateValueProperty(JsonReader reader, JsonProperty property, JsonConverter propertyConverter, object target, bool gottenCurrentValue, object currentValue)
{
JsonContract contract;
JsonConverter converter;
if (property.PropertyContract == null)
property.PropertyContract = GetContractSafe(property.PropertyType);
if (currentValue == null)
{
contract = property.PropertyContract;
converter = propertyConverter;
}
else
{
contract = GetContractSafe(currentValue.GetType());
if (contract != property.PropertyContract)
converter = GetConverter(contract, property.MemberConverter);
else
converter = propertyConverter;
}
Type objectType = property.PropertyType;
if (converter != null && converter.CanRead)
{
if (!gottenCurrentValue && target != null && property.Readable)
currentValue = property.ValueProvider.GetValue(target);
return converter.ReadJson(reader, objectType, currentValue, GetInternalSerializer());
}
return CreateValueInternal(reader, objectType, contract, property, currentValue);
}
示例11: SerializeConvertable
private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty))
{
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty))
return;
_serializeStack.Add(value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
converter.WriteJson(writer, value, GetInternalSerializer());
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
_serializeStack.RemoveAt(_serializeStack.Count - 1);
}
}
示例12: CalculatePropertyDetails
private bool CalculatePropertyDetails(JsonProperty property, ref JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target, out bool useExistingValue, out object currentValue, out JsonContract propertyContract, out bool gottenCurrentValue)
{
currentValue = null;
useExistingValue = false;
propertyContract = null;
gottenCurrentValue = false;
if (property.Ignored)
return true;
JsonToken tokenType = reader.TokenType;
if (property.PropertyContract == null)
property.PropertyContract = GetContractSafe(property.PropertyType);
ObjectCreationHandling objectCreationHandling =
property.ObjectCreationHandling.GetValueOrDefault(Serializer._objectCreationHandling);
if ((objectCreationHandling != ObjectCreationHandling.Replace)
&& (tokenType == JsonToken.StartArray || tokenType == JsonToken.StartObject)
&& property.Readable)
{
currentValue = property.ValueProvider.GetValue(target);
gottenCurrentValue = true;
if (currentValue != null)
{
propertyContract = GetContractSafe(currentValue.GetType());
useExistingValue = (!propertyContract.IsReadOnlyOrFixedSize && !propertyContract.UnderlyingType.IsValueType());
}
}
if (!property.Writable && !useExistingValue)
return true;
// test tokentype here because null might not be convertable to some types, e.g. ignoring null when applied to DateTime
if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore && tokenType == JsonToken.Null)
return true;
// test tokentype here because default value might not be convertable to actual type, e.g. default of "" for DateTime
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore)
&& !HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate)
&& JsonReader.IsPrimitiveToken(tokenType)
&& MiscellaneousUtils.ValueEquals(reader.Value, property.GetResolvedDefaultValue()))
return true;
if (currentValue == null)
{
propertyContract = property.PropertyContract;
}
else
{
propertyContract = GetContractSafe(currentValue.GetType());
if (propertyContract != property.PropertyContract)
propertyConverter = GetConverter(propertyContract, property.MemberConverter, containerContract, containerProperty);
}
return false;
}
示例13: CalculatePropertyDetails
private bool CalculatePropertyDetails(JsonProperty property, ref JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target, out bool useExistingValue, out object currentValue, out JsonContract propertyContract, out bool gottenCurrentValue)
{
currentValue = null;
useExistingValue = false;
propertyContract = null;
gottenCurrentValue = false;
if (property.Ignored)
{
reader.Skip();
return true;
}
ObjectCreationHandling objectCreationHandling =
property.ObjectCreationHandling.GetValueOrDefault(Serializer.ObjectCreationHandling);
if ((objectCreationHandling == ObjectCreationHandling.Auto || objectCreationHandling == ObjectCreationHandling.Reuse)
&& (reader.TokenType == JsonToken.StartArray || reader.TokenType == JsonToken.StartObject)
&& property.Readable)
{
currentValue = property.ValueProvider.GetValue(target);
gottenCurrentValue = true;
useExistingValue = (currentValue != null
&& !property.PropertyType.IsArray
&& !ReflectionUtils.InheritsGenericDefinition(property.PropertyType, typeof (ReadOnlyCollection<>))
&& !property.PropertyType.IsValueType());
}
if (!property.Writable && !useExistingValue)
{
reader.Skip();
return true;
}
// test tokentype here because null might not be convertable to some types, e.g. ignoring null when applied to DateTime
if (property.NullValueHandling.GetValueOrDefault(Serializer.NullValueHandling) == NullValueHandling.Ignore && reader.TokenType == JsonToken.Null)
{
reader.Skip();
return true;
}
// test tokentype here because default value might not be convertable to actual type, e.g. default of "" for DateTime
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer.DefaultValueHandling), DefaultValueHandling.Ignore)
&& JsonReader.IsPrimitiveToken(reader.TokenType)
&& MiscellaneousUtils.ValueEquals(reader.Value, property.GetResolvedDefaultValue()))
{
reader.Skip();
return true;
}
if (property.PropertyContract == null)
property.PropertyContract = GetContractSafe(property.PropertyType);
if (currentValue == null)
{
propertyContract = property.PropertyContract;
}
else
{
propertyContract = GetContractSafe(currentValue.GetType());
if (propertyContract != property.PropertyContract)
propertyConverter = GetConverter(propertyContract, property.MemberConverter, containerContract, containerProperty);
}
return false;
}
示例14: CreateValue
private object CreateValue(JsonReader reader, Type objectType, object existingValue, JsonConverter memberConverter)
{
JsonConverter converter;
if (memberConverter != null)
return memberConverter.ReadJson(reader, objectType, GetInternalSerializer());
if (objectType != null && _serializer.HasClassConverter(objectType, out converter))
return converter.ReadJson(reader, objectType, GetInternalSerializer());
if (objectType != null && _serializer.HasMatchingConverter(objectType, out converter))
return converter.ReadJson(reader, objectType, GetInternalSerializer());
if (objectType == typeof (JsonRaw))
return JsonRaw.Create(reader);
do
{
switch (reader.TokenType)
{
// populate a typed object or generic dictionary/array
// depending upon whether an objectType was supplied
case JsonToken.StartObject:
return CreateObject(reader, objectType, existingValue);
case JsonToken.StartArray:
return CreateList(reader, objectType, existingValue, null);
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Date:
return EnsureType(reader.Value, objectType);
case JsonToken.StartConstructor:
case JsonToken.EndConstructor:
string constructorName = reader.Value.ToString();
return constructorName;
case JsonToken.Null:
case JsonToken.Undefined:
if (objectType == typeof (DBNull))
return DBNull.Value;
return null;
case JsonToken.Comment:
// ignore
break;
default:
throw new JsonSerializationException("Unexpected token while deserializing object: " + reader.TokenType);
}
} while (reader.Read());
throw new JsonSerializationException("Unexpected end when deserializing object.");
}
示例15: TryConvertingFromStreamNullToSimpleObject
public void TryConvertingFromStreamNullToSimpleObject()
{
JsonConverter<ObjectWithName> converter = new JsonConverter<ObjectWithName>();
ObjectWithName objectExpected = converter.ConvertFrom(null);
Assert.IsTrue(objectExpected.Name == new ObjectWithName().Name);
}