本文整理汇总了C#中Newtonsoft.Json.JsonSerializer类的典型用法代码示例。如果您正苦于以下问题:C# JsonSerializer类的具体用法?C# JsonSerializer怎么用?C# JsonSerializer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
JsonSerializer类属于Newtonsoft.Json命名空间,在下文中一共展示了JsonSerializer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ReadJson
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;
}
示例2: WriteJson
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var representation = value as Representation;
if (representation != null)
representation.RepopulateHyperMedia();
var list = (IRepresentationList)value;
writer.WriteStartObject();
writer.WritePropertyName("_links");
serializer.Serialize(writer, list.Links);
writer.WritePropertyName("_embedded");
writer.WriteStartObject();
writer.WritePropertyName(list.Rel);
writer.WriteStartArray();
foreach (Representation halResource in list)
{
serializer.Serialize(writer, halResource);
}
writer.WriteEndArray();
writer.WriteEndObject();
var listType = list.GetType();
var propertyInfos = typeof(RepresentationList<>).GetProperties().Select(p => p.Name);
foreach (var property in listType.GetProperties().Where(p => !propertyInfos.Contains(p.Name)))
{
writer.WritePropertyName(property.Name.ToLower());
serializer.Serialize(writer, property.GetValue(value, null));
}
writer.WriteEndObject();
}
示例3: GetTypeFromJObject
private IElasticCoreType GetTypeFromJObject(JObject po, JsonSerializer serializer)
{
JToken typeToken;
serializer.TypeNameHandling = TypeNameHandling.None;
if (po.TryGetValue("type", out typeToken))
{
var type = typeToken.Value<string>().ToLowerInvariant();
switch (type)
{
case "string":
return serializer.Deserialize(po.CreateReader(), typeof(StringMapping)) as StringMapping;
case "float":
case "double":
case "byte":
case "short":
case "integer":
case "long":
return serializer.Deserialize(po.CreateReader(), typeof(NumberMapping)) as NumberMapping;
case "date":
return serializer.Deserialize(po.CreateReader(), typeof(DateMapping)) as DateMapping;
case "boolean":
return serializer.Deserialize(po.CreateReader(), typeof(BooleanMapping)) as BooleanMapping;
case "binary":
return serializer.Deserialize(po.CreateReader(), typeof(BinaryMapping)) as BinaryMapping;
}
}
return null;
}
示例4: WriteJson
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter" /> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var coordinateElements = value as List<LineString>;
if (coordinateElements != null && coordinateElements.Count > 0)
{
if (coordinateElements[0].Coordinates[0] != null)
{
writer.WriteStartArray();
foreach (var subPolygon in coordinateElements)
{
LineStringConverter.WriteJson(writer, subPolygon.Coordinates, serializer);
}
writer.WriteEndArray();
}
else
{
throw new NotImplementedException();
}
}
else
{
serializer.Serialize(writer, value);
}
}
示例5: ReadJsonWithInnerObjectTest
public void ReadJsonWithInnerObjectTest()
{
const string json = "{\"properties\":{\"test1\":\"value1\",\"test2\": { \"innertest1\":\"innervalue1\" }}}";
AttributesTableConverter target = new AttributesTableConverter();
using (JsonTextReader reader = new JsonTextReader(new StringReader(json)))
{
JsonSerializer serializer = new JsonSerializer();
// read start object token and prepare the next token
reader.Read();
reader.Read();
AttributesTable result =
(AttributesTable)
target.ReadJson(reader, typeof(AttributesTable), new AttributesTable(), serializer);
Assert.IsFalse(reader.Read()); // read the end of object and ensure there are no more tokens available
Assert.IsNotNull(result);
Assert.AreEqual(2, result.Count);
Assert.AreEqual("value1", result["test1"]);
Assert.IsNotNull(result["test2"]);
Assert.IsInstanceOf<IAttributesTable>(result["test2"]);
IAttributesTable inner = (IAttributesTable)result["test2"];
Assert.AreEqual(1, inner.Count);
Assert.AreEqual("innervalue1", inner["innertest1"]);
}
}
示例6: ReadJson
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;
}
示例7: ReadJson
//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);
}
}
示例8: ReadJson
/// <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;
}
示例9: ReadJson
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var reference = SupportedTypes[objectType].Invoke();
serializer.Populate(reader, reference);
return reference;
}
示例10: WriteJson
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">Serializer</param>
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, JsonSerializer serializer)
{
string text;
if (value is DateTime || value is DateTime?)
{
DateTime dateTime = value is DateTime ? (DateTime)value : (value as DateTime?).Value;
if ((dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
|| (dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
{
dateTime = dateTime.ToUniversalTime();
}
text = dateTime.ToString(ISODateTimeJsonConverter.DateTimeFormat, CultureInfo.InvariantCulture);
}
else
{
DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
if ((dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
|| (dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
dateTimeOffset = dateTimeOffset.ToUniversalTime();
text = dateTimeOffset.ToString(DateTimeFormat, CultureInfo.InvariantCulture);
}
writer.WriteValue(text);
}
示例11: Copy
public override void Copy(ODataObject source, JsonSerializer serializer)
{
if(source == null || serializer == null) return;
base.Copy(source, serializer);
var typedSource = source as Metadata;
if(typedSource != null)
{
Name = typedSource.Name;
Value = typedSource.Value;
IsPublic = typedSource.IsPublic;
}
else
{
JToken token;
if(source.TryGetProperty("Name", out token) && token.Type != JTokenType.Null)
{
Name = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
}
if(source.TryGetProperty("Value", out token) && token.Type != JTokenType.Null)
{
Value = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
}
if(source.TryGetProperty("IsPublic", out token) && token.Type != JTokenType.Null)
{
IsPublic = (bool?)serializer.Deserialize(token.CreateReader(), typeof(bool?));
}
}
}
示例12: WriteJson
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">Serializer</param>
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is DateTime || value is DateTime?)
{
DateTime date = value is DateTime ? (DateTime)value : (value as DateTime?).Value;
if (date != DateTime.MinValue)
{
writer.WriteValue(date.ToString(this.RenderMilliseconds ? DateTimeFormatMs : DateTimeFormat, CultureInfo.InvariantCulture));
}
else
{
writer.WriteRawValue("null");
}
return;
}
else
{
DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
if (dateTimeOffset != DateTimeOffset.MinValue)
{
writer.WriteValue(dateTimeOffset.ToString(DateTimeFormat, CultureInfo.InvariantCulture));
}
else
{
writer.WriteRawValue("null");
}
}
writer.WriteRawValue("null");
}
示例13: Json
public static string Json(Message message)
{
JsonSerializer js = new JsonSerializer();
StringWriter str=new StringWriter();
js.Serialize(str, message);
return str.ToString();
}
示例14: ReadJson
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;
}
开发者ID:foretagsplatsen,项目名称:Foretagsplatsen-DotNet-API,代码行数:25,代码来源:ChartOfAccountChildJsonConverter.cs
示例15: ReadJson
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;
}