I ran into some trouble trying to convert a class to a BSON document.
I have Custom1 and Custom2 which should behave a little different. How do I create a custom serializer which "unfold" the KeyValuePair so it generates the expected result (See below)? You can see the code example below together with the expected result.
Moreover, I'm using Mongo BSON library for serializing the object.
public class UserData
{
public UserData()
{
Id = 100;
Name = "Superuser";
Custom1 = new KeyValuePair<string, double>("HelloWorld1", 1);
Custom2 = new KeyValuePair<string, double>("HelloWorld2", 2);
}
public int Id { get; set; }
public string Name { get; set; }
public KeyValuePair<string, double> Custom1 { get; set; }
public KeyValuePair<string, double> Custom2 { get; set; }
}
Execute test code:
var userdata = new UserData();
var doc = userdata.ToBsonDocument();
Current result:
{
"Id": 100,
"Name": "Superuser",
"Custom1": {
"Key": "HelloWorld1",
"Value": 1
},
"Custom2": {
"Key": "HelloWorld2",
"Value": 2
}
}
Expected result:
{
"Id": 100,
"Name": "Superuser",
"HelloWorld1": 1,
"HelloWorld2": 2
}
For such a complex serialization case you have to implement custom IBsonSerializer converter for your class.
Here is the working example:
public class UserDataSerializer : SerializerBase<UserData>
{
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, UserData value)
{
context.Writer.WriteStartDocument();
context.Writer.WriteName("Id");
context.Writer.WriteInt32(value.Id);
context.Writer.WriteName("Name");
context.Writer.WriteString(value.Name);
WriteKeyValue(context.Writer, value.Custom1);
WriteKeyValue(context.Writer, value.Custom2);
context.Writer.WriteEndDocument();
}
private void WriteKeyValue(IBsonWriter writer, KeyValuePair<string, double> kv)
{
writer.WriteName(kv.Key);
writer.WriteDouble(kv.Value);
}
public override UserData Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
//TODO: implement data deserialization using context.Reader
throw new NotImplementedException();
}
}
To make it work you also need to register our UserDataSerializer somehow. IBsonSerializationProvider is the easiest way to achieve that.
public class UserDataSerializationProvider : IBsonSerializationProvider
{
public IBsonSerializer GetSerializer(Type type)
{
if (type == typeof(UserData)) return new UserDataSerializer();
return null;
}
}
And finally we can use it.
//register our serialization provider
BsonSerializer.RegisterSerializationProvider(new UserDataSerializationProvider());
var userdata = new UserData();
var doc = userdata.ToBsonDocument();
Here is the result:
{ "Id" : 100, "Name" : "Superuser", "HelloWorld1" : 1.0, "HelloWorld2" : 2.0 }
You may also want to implement UserDataSerializer.Deserialize() method in order to provide the backward conversion. It can be done in the same way using context.Reader.
More information about custom serialization process can be found here.
If you are using the driver 2.0 or higher, you could try to make your class into a DynamicObject, like this:
public class UserData : DynamicObject
{
public UserData()
{
Id = 100;
Name = "Superuser";
Custom1 = new KeyValuePair<string, double>("HelloWorld1", 1);
Custom2 = new KeyValuePair<string, double>("HelloWorld2", 2);
}
public id Id { get; set; }
public string Name { get; set; }
public KeyValuePair<string, double> Custom1 { get; set; }
public KeyValuePair<string, double> Custom2 { get; set; }
public override bool TryGetMember(
GetMemberBinder binder, out object result)
{
string name = binder.Name;
result = null;
if(name.Equals(Custom1.Key))
result = Custom1.Value;
else if(name.Equals(Custom2.Key))
result = Custom2.Value;
return result != null;
}
public override bool TrySetMember(
SetMemberBinder binder, object value)
{
string name = binder.Name;
if(name.Equals(Custom1.Key))
Custom1.Value = value;
else if(name.Equals(Custom2.Key))
Custom2.Value = value;
return name.Equals(Custom1.Key) ||
name.Equals(Custom2.Key);
}
}
According to the release documentation, you should then be able to do this:
var userdata = new UserData();
var doc = ((dynamic) userdata).ToBsonDocument();
And get the expected format.
Related
Given the following json:
[ {"id":"123", ... "data":[{"key1":"val1"}, {"key2":"val2"}], ...}, ... ]
that is part of a bigger tree, how can I deserialize the "data" property into:
List<MyCustomClass> Data { get; set; }
or
List<KeyValuePair> Data { get; set; }
or
Dictionary<string, string> Data { get; set; }
using Json.NET? Either version will do (I prefer List of MyCustomClass though). I already have a class that contains other properties, like this:
public class SomeData
{
[JsonProperty("_id")]
public string Id { get; set; }
...
public List<MyCustomClass> Data { get; set; }
}
where "MyCustomClass" would include just two properties (Key and Value). I noticed there is a KeyValuePairConverter class that sounds like it would do what I need, but I wasn't able to find an example on how to use it. Thanks.
The simplest way is deserialize array of key-value pairs to IDictionary<string, string>:
public class SomeData
{
public string Id { get; set; }
public IEnumerable<IDictionary<string, string>> Data { get; set; }
}
private static void Main(string[] args)
{
var json = "{ \"id\": \"123\", \"data\": [ { \"key1\": \"val1\" }, { \"key2\" : \"val2\" } ] }";
var obj = JsonConvert.DeserializeObject<SomeData>(json);
}
But if you need deserialize that to your own class, it can be looks like that:
public class SomeData2
{
public string Id { get; set; }
public List<SomeDataPair> Data { get; set; }
}
public class SomeDataPair
{
public string Key { get; set; }
public string Value { get; set; }
}
private static void Main(string[] args)
{
var json = "{ \"id\": \"123\", \"data\": [ { \"key1\": \"val1\" }, { \"key2\" : \"val2\" } ] }";
var rawObj = JObject.Parse(json);
var obj2 = new SomeData2
{
Id = (string)rawObj["id"],
Data = new List<SomeDataPair>()
};
foreach (var item in rawObj["data"])
{
foreach (var prop in item)
{
var property = prop as JProperty;
if (property != null)
{
obj2.Data.Add(new SomeDataPair() { Key = property.Name, Value = property.Value.ToString() });
}
}
}
}
See that I khow that Value is string and i call ToString() method, there can be another complex class.
Thanks #Boo for your answer but in my case I needed to take some small adjustements.
This is how my JSON looks like:
{
"rates": {
"CAD": 1.5649,
"CZK": 26.118,
...
},
"base": "EUR",
"date": "2020-08-16"
}
And my DTO looks like the following:
public IDictionary<string, decimal> Rates { get; set; }
public string Base { get; set; }
public DateTime Date { get; set; }
So the only adjustement was to remove the IEnumerable around the IDictionary.
I ended up doing this:
[JsonConverter(typeof(MyCustomClassConverter))]
public class MyCustomClass
{
internal class MyCustomClassConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jObject = JObject.Load(reader);
foreach (var prop in jObject)
{
return new MyCustomClass { Key = prop.Key, Value = prop.Value.ToString() };
}
return null;
}
public override bool CanConvert(Type objectType)
{
return typeof(MyCustomClass).IsAssignableFrom(objectType);
}
}
public string Key { get; set; }
public string Value { get; set; }
}
public class Datum
{
public string key1 { get; set; }
public string key2 { get; set; }
}
public class RootObject
{
public string id { get; set; }
public List<Datum> data { get; set; }
}
i used this wizard as well json2csharp.com to generate class for deserialized
for using that
using RestSharp;
using Newtonsoft.Json;
IRestResponse restSharp= callRestGetMethodby_restSharp(api_server_url);
string jsonString= restSharp.Content;
RootObject rootObj= JsonConvert.DeserializeObject<RootObject>(jsonString);
return Json(rootObj);
if you call rest by restsharp
public IRestResponse callRestGetMethodby_restSharp(string API_URL)
{
var client = new RestSharp.RestClient(API_URL);
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("cache-control", "no-cache");
IRestResponse response = client.Execute(request);
return response;
}
also you can get this 6 line of restsharp from getpostman.com tools
You can use public IEnumerable<IDictionary<string, string>> Data as the most answers are recommending, but it is not the best idea, since it creates a new dictionary for each array key value item. I recommend to use List<KeyValuePair<string, string>> instead ( or you can create a custom class as well instead of using KeyValuePair )
var json = "[{ \"id\": \"123\", \"data\": [ { \"key1\": \"val1\" }, { \"key2\" : \"val2\" } ] }]";
List<SomeData> listSomeData = JsonConvert.DeserializeObject<List<SomeData>>(json);
public class SomeData
{
[JsonProperty("id")]
public string Id { get; set; }
public List<KeyValuePair<string, string>> Data { get; set; }
[JsonConstructor]
public SomeData(JArray data)
{
Data = data.Select(d => new KeyValuePair<string, string>(
((JObject)d).Properties().First().Name,
((JObject)d).Properties().First().Value.ToString()))
.ToList();
}
}
I have an Azure Server-less Function that serves to take in a JSON payload and work on the records contained. The function works perfectly well to do what is intended except it shouldn't matter the wrapper node name. For example:
{
"Wrapper": [{
"Field1": "Apple",
"Field2": "Peach",
"Field3": "########5",
"Field4": "Kiwi",
}]
}
Should be processed the same way as:
{
"OtherWrapperName": [{
"Column1": "Apple",
"Something": "Peach",
"SomethingElse": "Banana",
"Field4": "Kiwi"
}]
}
Right now it seems to expect the top level node to be called "Wrapper". Here is my attempt at this (some code has been redacted as it was unnecessary for this example):
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
string InputData = await req.Content.ReadAsStringAsync();
var inputData = JsonConvert.DeserializeObject<ItemsPayload>(InputData);
var propertiesLookup = new Dictionary<string, ItemUpdate>();
var propertiesRequest = new PropertySearchRequest { Registry = new List<RequestPropertySearch>() };
int recordCounter = 0;
foreach (var item in inputData.Wrapper)
{
foreach (var kvp in item.Where(property => property.Value.StartsWith("#!!!#")))
{
propertiesLookup[recordCounter.ToString() + "|" + kvp.Value] = new ItemUpdate
{
Properties = item,
UpdateKey = kvp.Key
};
propertiesRequest.Registry.Add(new RequestPropertySearch
{
Token = kvp.Value
});
recordCounter++;
}
}
var intermediateRequest = JsonConvert.SerializeObject(propertiesRequest, Formatting.Indented);
HttpResponseMessage response = MakeRequest(serviceUrl, intermediateRequest, securityHeaderName, securityHeaderValue);
var responseBodyAsText = response.Content.ReadAsStringAsync();
var intermediateData = JsonConvert.DeserializeObject<PropertySearchResponse>(responseBodyAsText.Result);
recordCounter = 0;
foreach (var item in intermediateData.Registry)
{
if (item.Value != null)
{
var itemToUpdate = propertiesLookup[recordCounter.ToString() + "|" + item.Token];
itemToUpdate.Properties[itemToUpdate.UpdateKey] = item.Value;
if (directive.ToLower() == "s")
{
itemToUpdate.Properties[$"#{itemToUpdate.UpdateKey}"] = item.Token;
}
// recordCounter++;
}
recordCounter++;
}
var result = JsonConvert.SerializeObject(inputData, Formatting.Indented);
//return req.CreateResponse(HttpStatusCode.OK, "");
return new HttpResponseMessage()
{
Content = new StringContent(result, System.Text.Encoding.UTF8, "application/json")
};
}
Models:
public class ItemsPayload
{
//public string Directive { get; set; }
public List<Dictionary<string, string>> Wrapper { get; set; }
}
public class PropertySearchRequest
{
public List<RequestPropertySearch> Registry { get; set; }
}
public class RequestPropertySearch
{
public string Token { get; set; }
}
public class PropertySearchResponse
{
public List<ResponsePropertySearch> Registry { get; set; }
}
public class ResponsePropertySearch
{
public string Token { get; set; }
public string Value { get; set; }
public string ProcessId { get; set; }
public string Code { get; set; }
public string Remote { get; set; }
public string Message { get; set; }
}
public class ItemUpdate
{
public Dictionary<string, string> Properties { get; set; }
public string UpdateKey { get; set; }
}
I think the ItemsPayload class property "Wrapper" is causing this as if you change that to something else and rename the node in the JSON it works fine, but I want it to be independent of the name of the top level node. Any thoughts?
You could create a simple JsonConverter for your ItemsPayload to handle the varying wrapper name.
public class ItemsPayloadConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(ItemsPayload);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject obj = JObject.Load(reader);
ItemsPayload payload = new ItemsPayload();
// Get the first property of the outer JSON object regardless of its name
// and populate the payload from it
JProperty wrapper = obj.Properties().FirstOrDefault();
if (wrapper != null)
{
payload.Wrapper = wrapper.Value.ToObject<List<Dictionary<string, string>>>(serializer);
}
return payload;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Then, just annotate your ItemsPayload class with a [JsonConverter] attribute like this and it should work with no other changes to your code:
[JsonConverter(typeof(ItemsPayloadConverter))]
public class ItemsPayload
{
public List<Dictionary<string, string>> Wrapper { get; set; }
}
Fiddle: https://dotnetfiddle.net/9q4tgW
I have some JSON that can come in two different formats. Sometimes the location value is a string, and sometimes it is an object. This is a sample of the first format:
{
"result": [
{
"upon_approval": "Proceed to Next Task",
"location": "",
"expected_start": ""
}
]
}
Class definitions for this:
public class Result
{
public string upon_approval { get; set; }
public string location { get; set; }
public string expected_start { get; set; }
}
public class RootObject
{
public List<Result> result { get; set; }
}
Here is the JSON in the second format:
{
"result": [
{
"upon_approval": "Proceed to Next Task",
"location": {
"display_value": "Corp-HQR",
"link": "https://satellite.service-now.com/api/now/table/cmn_location/4a2cf91b13f2de00322dd4a76144b090"
},
"expected_start": ""
}
]
}
Class definitions for this:
public class Location
{
public string display_value { get; set; }
public string link { get; set; }
}
public class Result
{
public string upon_approval { get; set; }
public Location location { get; set; }
public string expected_start { get; set; }
}
public class RootObject
{
public List<Result> result { get; set; }
}
When deserializing, I get errors when the JSON format does not match my classes, but I don't know ahead of time which classes to use because the JSON format changes. So how can I dynamically get these two JSON formats to deserialize into one set of classes?
This is how I am deserializing now:
JavaScriptSerializer ser = new JavaScriptSerializer();
ser.MaxJsonLength = 2147483647;
RootObject ro = ser.Deserialize<RootObject>(responseValue);
To solve this problem you'll need to make a custom JavaScriptConverter class and register it with the serializer. The serializer will load the result data into a Dictionary<string, object>, then hand off to the converter, where you can inspect the contents and convert it into a usable object. In short, this will allow you to use your second set of classes for both JSON formats.
Here is the code for the converter:
class ResultConverter : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get { return new List<Type> { typeof(Result) }; }
}
public override object Deserialize(IDictionary<string, object> dict, Type type, JavaScriptSerializer serializer)
{
Result result = new Result();
result.upon_approval = GetValue<string>(dict, "upon_approval");
var locDict = GetValue<IDictionary<string, object>>(dict, "location");
if (locDict != null)
{
Location loc = new Location();
loc.display_value = GetValue<string>(locDict, "display_value");
loc.link = GetValue<string>(locDict, "link");
result.location = loc;
}
result.expected_start = GetValue<string>(dict, "expected_start");
return result;
}
private T GetValue<T>(IDictionary<string, object> dict, string key)
{
object value = null;
dict.TryGetValue(key, out value);
return value != null && typeof(T).IsAssignableFrom(value.GetType()) ? (T)value : default(T);
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
}
Then use it like this:
var ser = new JavaScriptSerializer();
ser.MaxJsonLength = 2147483647;
ser.RegisterConverters(new List<JavaScriptConverter> { new ResultConverter() });
RootObject ro = serializer.Deserialize<RootObject>(responseValue);
Here is a short demo:
class Program
{
static void Main(string[] args)
{
string json = #"
{
""result"": [
{
""upon_approval"": ""Proceed to Next Task"",
""location"": {
""display_value"": ""Corp-HQR"",
""link"": ""https://satellite.service-now.com/api/now/table/cmn_location/4a2cf91b13f2de00322dd4a76144b090""
},
""expected_start"": """"
}
]
}";
DeserializeAndDump(json);
Console.WriteLine(new string('-', 40));
json = #"
{
""result"": [
{
""upon_approval"": ""Proceed to Next Task"",
""location"": """",
""expected_start"": """"
}
]
}";
DeserializeAndDump(json);
}
private static void DeserializeAndDump(string json)
{
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new List<JavaScriptConverter> { new ResultConverter() });
RootObject obj = serializer.Deserialize<RootObject>(json);
foreach (var result in obj.result)
{
Console.WriteLine("upon_approval: " + result.upon_approval);
if (result.location != null)
{
Console.WriteLine("location display_value: " + result.location.display_value);
Console.WriteLine("location link: " + result.location.link);
}
else
Console.WriteLine("(no location)");
}
}
}
public class RootObject
{
public List<Result> result { get; set; }
}
public class Result
{
public string upon_approval { get; set; }
public Location location { get; set; }
public string expected_start { get; set; }
}
public class Location
{
public string display_value { get; set; }
public string link { get; set; }
}
Output:
upon_approval: Proceed to Next Task
location display_value: Corp-HQR
location link: https://satellite.service-now.com/api/now/table/cmn_location/4a2cf91b13f2de00322dd4a76144b090
----------------------------------------
upon_approval: Proceed to Next Task
(no location)
I'm working on a .NET application for my company to interact with the Nutshell CRM. They have documentation provided for their JSON API here. I'm slowly building out all the classes in my application, but I've run into the issue of only needing to update one field on a call, but having the application include every field that I have on that class.
So for a condensed example of the editLead method, where I'm only modifying the customFields:
Nutshell documentation states that all fields are optional. My classes are set up as the following, where my custom fields in Nutshell are Division, Product, Country:
public class editLead
{
public Customfields customFields { get; set; }
}
public class Customfields
{
public string Division { get; set; }
public string Product { get; set; }
public string Country { get; set; }
}
EDIT (adding more code):
[DataContract(Name = "params")]
public class EditLeadParams
{
public string leadId { get; set; }
public editLead lead { get; set; }
public string rev { get; set; }
}
I'm using RestSharp to make the following call:
var editleadclient = new RestClient();
Method editleadMethod = new Method();
editleadMethod = Method.POST;
var editleadrequest = new RestRequest(editleadMethod);
editleadrequest.RequestFormat = DataFormat.Json;
editleadclient.BaseUrl = new Uri(apiuri);
editleadrequest.Credentials = new NetworkCredential(login, apikey);
leadJSON.EditLeadParams lead1 = new leadJSON.EditLeadParams()
{
leadId = foundlead[0],
lead = new leadJSON.editLead()
{
customFields = new leadJSON.Customfields()
{
Division = "AMERICAS",
}
},
rev = foundlead[1],
};
leadJSON.EditLeadRequest editreq = new leadJSON.EditLeadRequest()
{
#params = lead1,
method = "editLead",
};
editleadrequest.AddBody(editreq);
IRestResponse editResponse = editleadclient.Execute(editleadrequest);
If I only want to update the Division, it will use the following JSON {"customFields":{"Division":"AMERICAS","Product":null,"Country":null}}, and overwrite the Product and Country fields and make them blank. However, if I comment out the Product and Country, in the Customfields definition, it will update the Division and leave the Product and Country alone.
Is there another way to define these classes so that I can have it all defined, but only update what needs to be?
Declaration:
//JsonSerializer.cs
public static class JsonSerializer
{
public static string Serialize(object target, bool ignoreNulls = true)
{
var javaScriptSerializer = new JavaScriptSerializer();
if (ignoreNulls)
{
javaScriptSerializer.RegisterConverters(new[]
{
new NullExclusionConverter(target)
});
}
return javaScriptSerializer.Serialize(target);
}
}
//NullExclusionConverter.cs
public class NullExclusionConverter : JavaScriptConverter
{
private readonly Type _type;
public NullExclusionConverter(object target)
{
if (target == null)
{
throw new ArgumentNullException("target");
}
this._type = target.GetType();
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IEnumerable<Type> SupportedTypes
{
get
{
return new[] { this._type };
}
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var result = new Dictionary<string, object>();
if (obj == null)
{
return result;
}
var properties = obj.GetType().GetProperties();
foreach (var propertyInfo in properties)
{
//Use propertyInfo.Name to exclude a specific property name
if (propertyInfo.GetValue(obj, null) == null)
{
continue;
}
result.Add(propertyInfo.Name, propertyInfo.GetValue(obj, null));
}
return result;
}
}
Usage:
string jsonString = JsonSerializer.Serialize(objectToSerialize);
Add a reference to System.Web.Extensions
I am leaving my initial answer because it does return only non-null properties as a Json string. However here is your answer when using RestSharp.
On your request add:
editleadrequest.JsonSerializer.Options = new SerializerOptions()
{
SkipNullProperties = true
};
I have a class that calls a webservice which returns a JSON string which I need to deserialize into a C# object. I was successfully able to do this; however, I came across a scenario that I am not sure exactly the best way to handle. More specifically, the JSON will either return a List<List<object>> or just a List<object>. I am having a problem when I deserialize if my object is List<object> and the JSON is List<List<object>>. In that case, an exception is thrown.
This is class that I am trying to deserialize:
public class WorkOrderJson
{
public string type { get; set; }
public Properties properties { get; set; }
public Geometry geometry { get; set; }
}
public class Properties
{
public string FeatureType { get; set; }
public string WorkOrderID { get; set; }
public string EqEquipNo { get; set; }
}
For the Geometry class the coordinates returned are the issue from above. If the JSON returned is a List<List<object>> it serializes fine.
public class Geometry
{
public string type { get; set; }
public List<List<double>> coordinates { get; set; }
}
This is how I am performing deserialization:
WorkOrderJson workOrderJson = new JavaScriptSerializer().Deserialize<List<WorkOrderJson>>(responseString);
where responseString is the JSON string returned from web service. Hope this makes sense. If anybody has come across a similar issue, any help would be much appreciated.
Here is an example for List<List<object>> where coordinates is the list:
[
{
"type": "Feature",
"properties": {
"FeatureType": "WORKORDER",
"WorkOrderID": "AMO172-2015-107",
"EqEquipNo": "AC-LIN-001"
},
"geometry": {
"type": "LineString",
"coordinates": [
[
-111.00041804208979,
33.0002148138019
],
[
-111.00027869450028,
33.000143209356054
]
]
},
"symbology": {
"color": "#990000",
"lineWidth": "8"
}
}
]
Here is an example for List<object>:
[
{
"type": "Feature",
"properties": {
"FeatureType": "WORKORDER",
"WorkOrderID": "AMO172-2015-115",
"EqEquipNo": "AC-LIN-001"
},
"geometry": {
"type": "Point",
"coordinates": [
-111.00041804208979,
33.0002148138019
]
}
}
]
So for anyone that cares changing the Geometry Class to the following solved my problem:
public class Geometry
{
public string type { get; set; }
public object coordinates { get; set; }
}
Just changed list to object. Then at runtime i can check whether the object is list of lists or just a list and proceed.
Create a custom JavaScriptConverter and register it with your JavaScriptSerializer.
You would then deserialize like this:
var converter = new JavaScriptSerializer();
converter.RegisterConverters(new List<JavaScriptConverter>() {new GeometryConverter()});
var workOrderJson = converter.Deserialize<List<WorkOrderJson>>(response);
This converter would work:
public class GeometryConverter : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get { return new List<Type>(new Type[] {typeof(Geometry)}); }
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
Geometry geometry = obj as Geometry;
if (geometry != null)
{
// Create the representation
var result = new Dictionary<string, object>();
if (geometry.coordinates.Count == 1)
{
result.Add("type", "Point");
result.Add("coordinates", geometry.coordinates[0]);
}
else if (geometry.coordinates.Count > 1)
{
result.Add("type", "LineString");
result.Add("coordinates", geometry.coordinates);
}
return result;
}
return new Dictionary<string, object>();
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
Geometry geometry = null;
if (type == typeof(Geometry))
{
geometry = new Geometry();
geometry.type = (string)dictionary["type"];
geometry.coordinates = new List<List<double>>();
if ( geometry.type == "Point")
{
ArrayList arrayList = (ArrayList)dictionary["coordinates"];
geometry.coordinates.Add(ConvertCoordinates(arrayList));
}
else if (geometry.type == "LineString")
{
geometry.type = "LineString";
ArrayList coordinatesList = (ArrayList)dictionary["coordinates"];
foreach (ArrayList arrayList in coordinatesList)
{
geometry.coordinates.Add(ConvertCoordinates(arrayList));
}
}
}
return geometry;
}
private List<double> ConvertCoordinates(ArrayList coordinates)
{
var list = new List<double>();
foreach (var coordinate in coordinates)
{
list.Add((double)System.Convert.ToDouble(coordinate));
}
return list;
}
}
If I understand and you are trying to deserialize a List<List<a>> as a List<a>, it should error. You're telling it to deserialize it into something other than what it was before serialization. I would recommend either propagating some indication of which it is along with the string so you can check and deserialize as that type, or wrap the deserialization attempts and try one first, then the other if it fails.
Edit per update
public class WorkOrderJson<T>
{
public Geometry<T> geometry { get; set; }
public WorkOrderJson<List<T>> Promote()
{
var temp = new WorkOrderJson<List<T>>();
temp.geometry = geometry.Promote();
return temp;
}
}
public class Geometry<T>
{
public T coordinates { get; set; }
public Geometry<List<T>> Promote()
{
var temp = new Geometry<List<T>>();
temp.coordinates = new List<T>(){ coordinates };
return temp;
}
}
public List<WorkOrder<List<List<double>>>> Deserialize(string x)
{
try
{
return new JavaScriptSerializer().Deserialize<List<WorkOrderJson<List<List<double>>>>>(x);
}
catch(InvalidOperationException ex)
{
return new JavaScriptSerializer().Deserialize<List<WorkOrderJson<List<double>>>>(x).Select(workOrder => workOrder.Promote());
}
}