C# Client Library
A C# Client Library for the AnalyzeRe REST API
Loading...
Searching...
No Matches
PortfolioViewSerializer.cs
Go to the documentation of this file.
1using System;
2using System.Linq;
3using Newtonsoft.Json;
4
6{
12 public class PortfolioViewSerializer : JsonConverter
13 {
20 public override bool CanConvert(Type objectType)
21 {
22 return typeof(PortfolioView).IsAssignableFrom(objectType);
23 }
24
33 public override object ReadJson(
34 JsonReader reader,
35 Type objectType,
36 object existingValue,
37 JsonSerializer serializer)
38 {
39 if (reader.TokenType == JsonToken.Null)
40 return null;
41 PortfolioView target = new PortfolioView();
42 serializer.Populate(reader, target);
43 return target;
44 }
45
50 public override void WriteJson(
51 JsonWriter writer,
52 object value,
53 JsonSerializer serializer)
54 {
55 if (value == null)
56 {
57 writer.WriteNull();
58 return;
59 }
60 if (!(value is PortfolioView pv))
61 throw new InvalidOperationException($"Unhandled case for PortfolioViewSerializer. " +
62 $"Unexpected non-PortfolioView value: {value}");
63
64 // We want to serialize using the current serializer settings,
65 // but use the default serializing behaviour (to avoid infinite recursion).
66 // TODO: Have to revisit this if ever a portfolio_view can reference another portfolio_view.
67 // In that case we'll have to serialize the current level manually, and invoke
68 // the current unmodified serializer on each member.
69 JsonSerializerSettings recurseSettings = serializer.GetJsonSerializerSettings();
70 recurseSettings.Converters.Remove(
71 serializer.Converters.OfType<PortfolioViewSerializer>().Cast<JsonConverter>().Single());
72 JsonSerializer recurseSerializer = JsonSerializer.Create(recurseSettings);
73
74 if (pv.layer_views == null || pv.portfolio == null)
75 recurseSerializer.Serialize(writer, pv);
76 else
77 {
78 // If the user has specified a portfolio reference, and the layer_views collection
79 // is empty but isn't null, we should set it to null or the server will complain
80 // that both were specified, while layer_views being empty should be treated as null.
81 PortfolioView pvFixed = pv.ShallowCopy();
82 if (!pv.layer_views.Any())
83 pvFixed.layer_views = null;
84 // If the user actually supplied both, they will get an error as expected
85 recurseSerializer.Serialize(writer, pvFixed);
86 }
87 }
88 }
89}
Allows serializing and deserializing PortfolioViews, which require a special rule since they can only...
override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
Parses the json to the specified type.
override bool CanConvert(Type objectType)
Determines if this converter is designed for deserialization to objects of the specified type.
override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
Serializes to the specified type.
Represents the Analysis of a Portfolio.