I currently am getting a JSON object with a shape similar to the following:
{
more data here...
"years": {
"value": 2013,
"item1": {
"total": 0.1044,
"Low": 0.0143,
"Mid": 0.1044,
"High": 0.3524,
"min": 0.0143,
"max": 0.3524,
},
"item2": {
"total": 0.1702,
"Low": 0.167,
"Mid": 0.1702,
"High": 0.1737,
"min": 0.167,
"max": 0.1737,
},...
}
}
I unfortunately, have no control over the shape of the JSON.
I am trying to get RestSharp to deserialize this into an object where Item1, Item2, and the rest fill into a Dictionary I currently have the following code:
public class Year
{
public int Value { get; set; }
public Dictionary<string, Data> Data { get; set; }
}
public class Data
{
public decimal Total { get; set; }
public decimal Low { get; set; }
public decimal Mid { get; set; }
public decimal High { get; set; }
public decimal Min { get; set; }
public decimal Max { get; set; }
}
And I am hoping to get Item1, Item2, etc. to be the keys of the Dictionary and the values underneath to fill in the Data class as the value of the Dictionary. But it isn't working at the moment (the rest of my structure is, it's just this innermost part). Am I just approaching the structure wrong? I want to avoid having to create a specific class for Item1 and Item2.
You could use a custom JsonConverter:
public class YearConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Year);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var obj = JObject.Load(reader);
int year = (int)obj["value"];
var data = new Dictionary<string, Data>();
foreach (var dataItem in obj.Children()
.OfType<JProperty>()
.Where(p => p.Name.StartsWith("item")))
{
data.Add(dataItem.Name, dataItem.Value.ToObject<Data>());
}
return new Year
{
Value = year,
Data = data
};
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Decorate your Year class with the converter:
[JsonConverter(typeof(YearConverter))]
public class Year
{
public int Value { get; set; }
public Dictionary<string, Data> Data { get; set; }
}
Using it like this, for example:
class Program
{
static void Main(string[] args)
{
string json = #"
{
""value"": 2013,
""item1"": {
""total"": 0.1044,
""Low"": 0.0143,
""Mid"": 0.1044,
""High"": 0.3524,
""min"": 0.0143,
""max"": 0.3524,
},
""item2"": {
""total"": 0.1702,
""Low"": 0.167,
""Mid"": 0.1702,
""High"": 0.1737,
""min"": 0.167,
""max"": 0.1737,
}
}";
var years = JsonConvert.DeserializeObject<Year>(json);
}
}
Steps:
1. Always shape your JSON object in a logical way
This issue would be significantly easier to handle if you restructured your json object in a more logical way. Right now you have n number of data objects at the same level as "value" and you are changing their property names dynamically.
Personally, I would reshape the json as such:
{
"years":[
{
"value":2013,
"data":[
{
"name":"item1",
"total":0.1044,
"Low":0.0143,
"Mid":0.1044,
"High":0.3524,
"min":0.0143,
"max":0.3524
},
{
"name":"item2",
"total":0.1702,
"Low":0.167,
"Mid":0.1702,
"High":0.1737,
"min":0.167,
"max":0.1737
}
]
}
]
}
Step 2: Add the Newtonsoft.Json attributes to your classes
This allows for easy deserialization
public class Base
{
[JsonProperty("years")]
public List<Year> years { get; set; }
}
public class Year
{
[JsonProperty("value")]
public int Value { get; set; }
[JsonProperty("data")]
public List<Data> data { get; set; }
}
public class Data
{
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("total")]
public decimal Total { get; set; }
[JsonProperty("Low")]
public decimal Low { get; set; }
[JsonProperty("Mid")]
public decimal Mid { get; set; }
[JsonProperty("High")]
public decimal High { get; set; }
[JsonProperty("min")]
public decimal Min { get; set; }
[JsonProperty("max")]
public decimal Max { get; set; }
}
Step 3: Deserialize it
Base myYears = JsonConvert.DeserializeObject<Base>(myJsonString);
Related
API retuned json object like below 2 forms.
Form 1
{
"Pricing": [
{
"total": 27,
"currency": "USD",
"charges": [ //Chargers Array
{
"code": "C1",
"currency": "USD",
"rate": 15
},
{
"code": "C45",
"currency": "USD",
"rate": 12
}
]
}
]
}
Form 2
{
"Pricing": [
{
"total": 12,
"currency": "USD",
"charges": { //Chargers single object
"code": "C1",
"currency": "USD",
"rate": 12
}
}
]
}
As you can see sometime chargers object return with array and some times not. My question is how to parse this to C# class object? If I added the C# class like below it cannot be parse properly for Form 2. (Form 1 parsing properly)
public class Charge
{
public string code { get; set; }
public string currency { get; set; }
public decimal rate { get; set; }
}
public class Pricing
{
public decimal total { get; set; }
public string currency { get; set; }
public List<Charge> charges { get; set; } //In Form 2, this should be single object
}
public class MainObj
{
public List<Pricing> Pricing { get; set; }
}
Error occurred when parse with Newtonsoft deserialization.
MainObj obj = JsonConvert.DeserializeObject<MainObj>(json);
Error
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type 'System.Collections.Generic.List`1[Charge]' because the type
requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix
this error either change the JSON to a JSON array (e.g. [1,2,3]) or
change the deserialized type so that it is a normal .NET type (e.g.
not a primitive type like integer, not a collection type like an array
or List) that can be deserialized from a JSON object.
JsonObjectAttribute can also be added to the type to force it to
deserialize from a JSON object. Path 'Pricing[0].charges.code', line
1, position 69.
Any common method for parsing, when receiving different type of object types with C#?
(I look into this as well but it's for java. And most of this kind of question raised for java but not C#.)
Yet another way of dealing with this problem is to define a custom JsonConverter which can handle both cases.
class ArrayOrObjectConverter<T> : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader);
return token.Type == JTokenType.Array
? token.ToObject<List<T>>()
: new List<T> { token.ToObject<T>() };
}
public override bool CanConvert(Type objectType)
=> objectType == typeof(List<T>);
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
=>throw new NotImplementedException();
}
Inside the ReadJson first we get a JToken to be able to determine the read value's Type (kind)
Based on that the we can either call ToObject<List<T>> or ToObject<T>
Inside the CanConvert we examine that the to be populated property's type is a List<T>
Even though there is a generic JsonConverter<T> where you don't have to define the CanConvert, its ReadJson can be implemented in a bit more complicated way
Since the question is all about deserialization I've not implemented the WriteJson method
You might also consider to override the CanWrite property of the base class to always return false
With this class in our hand you can decorate your properties with a JsonConverterAttribute to tell to the Json.NET how to deal with those properties
public class Pricing
{
public decimal total { get; set; }
public string currency { get; set; }
[JsonConverter(typeof(ArrayOrObjectConverter<Charge>))]
public List<Charge> charges { get; set; }
...
}
You could go for an approach to try and parse Form1's object to json, if it fails it will use Form2's object to json.
Example here and below: https://dotnetfiddle.net/F1Yh25
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
string form1 = "{\"Pricing\":[{\"total\":27,\"currency\":\"USD\",\"charges\":[{\"code\":\"C1\",\"currency\":\"USD\",\"rate\":15},{\"code\":\"C45\",\"currency\":\"USD\",\"rate\":12}]}]}";
string form2 = "{\"Pricing\":[{\"total\":12,\"currency\":\"USD\",\"charges\":{\"code\":\"C1\",\"currency\":\"USD\",\"rate\":12}}]}";
string json = form1;//Change form1 to form2 and it will also work
try
{
Form1.Root Object = JsonConvert.DeserializeObject<Form1.Root>(json);
Console.WriteLine("Item 1's Pricing: " + Object.Pricing[0].total);
}
catch//If Form1's json is Form2 it will catch here
{
Form2.Root Object = JsonConvert.DeserializeObject<Form2.Root>(json);
Console.WriteLine("Item 1's Pricing: " + Object.Pricing[0].total);
}
}
public class Form1
{
public class Charge
{
public string code { get; set; }
public string currency { get; set; }
public int rate { get; set; }
}
public class Pricing
{
public int total { get; set; }
public string currency { get; set; }
public List<Charge> charges { get; set; }
}
public class Root
{
public List<Pricing> Pricing { get; set; }
}
}
public class Form2
{
public class Charges
{
public string code { get; set; }
public string currency { get; set; }
public int rate { get; set; }
}
public class Pricing
{
public int total { get; set; }
public string currency { get; set; }
public Charges charges { get; set; }
}
public class Root
{
public List<Pricing> Pricing { get; set; }
}
}
}
Ok so here is another way to do this without having to use two classes and not having a try catch. Basically just update Pricing class to following and it works for both cases. Probably a better way but this is better (at least in my opinion) and having two classes and having try catch do your branching. If you had ten properties with this issue would you then create 10! classes to handle every combo? No way lol!
public class Pricing {
public int total { get; set; }
public string currency { get; set; }
private List<Charge> _charges;
public object charges {
get {
return _charges;
}
set {
if(value.GetType().Name == "JArray") {
_charges = JsonConvert.DeserializeObject<List<Charge>>(value.ToString());
}
else {
_charges = new List<Charge>();
var charge = JsonConvert.DeserializeObject<Charge>(value.ToString());
_charges.Add(charge);
}
}
}
}
I'm currently dealing with getting data from an external API. The data I receive looks something like what is shown below. (Just a mockup; don't expect the values to make any sense. It's just to illustrate what kind of data I get.)
{
"user": [
{
"key": "12345678",
"data": [
{
"id": "Name",
"string": "Bob"
},
{
"id": "ElapsedTimeSinceLastMessage",
"timestamp": 1618233964000
},
{
"id": "Age",
"number": 27
}
]
}
]
}
I don't really know how I should be going about deserializing this JSON.
The classes I'm using to deserialize right now look like this:
public class User
{
[JsonProperty("key")]
public string Key { get; set; }
[JsonProperty("data")]
public List<DataEntry> DataEntries { get; set; }
}
public class DataEntry
{
[JsonProperty("id")]
public string Id { get; set; }
public Type Value { get; set; }
}
And I don't know what I need to set in order to deserialize the Value inside the DataEntry. Maybe someone can guide me into the right direction?
The Data part of this JSON is really just a Dictionary<string, object> in disguise. You can use a custom JsonConverter to transform the list of id/value pairs into that format for easy use.
Frist, define these classes:
class RootObject
{
[JsonProperty("user")]
public List<User> Users { get; set; }
}
class User
{
public string Key { get; set; }
[JsonConverter(typeof(CustomDataConverter))]
public Dictionary<string, object> Data { get; set; }
}
Next, define the converter:
class CustomDataConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Dictionary<string, object>);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return JToken.Load(reader)
.Children<JObject>()
.ToDictionary(jo => (string)jo["id"],
jo => jo.Properties()
.Where(jp => jp.Name != "id" && jp.Value is JValue)
.Select(jp => ((JValue)jp.Value).Value)
.FirstOrDefault());
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
You can then deserialize and dump out the data like this:
var root = JsonConvert.DeserializeObject<RootObject>(json);
foreach (User user in root.Users)
{
Console.WriteLine("User Key: " + user.Key);
foreach (var kvp in user.Data)
{
Console.WriteLine(kvp.Key + ": " + kvp.Value);
}
}
Here is a working demo: https://dotnetfiddle.net/GIT4dl
One angle of attack would be with Dictionaries:
public class WithUser
{
public List<User> User { get; set; }
}
public class User
{
[JsonProperty("key")]
public string Key { get; set; }
[JsonProperty("data")]
public List<Dictionary<string,object>> DataEntries { get; set; }
}
The extraction is a bit of a pain but possible:
public static void Main()
{
var json = File.ReadAllText("Example.json");
var x = JsonConvert.DeserializeObject<WithUser>(json);
var user = x.User.Single();
var age = Extract<long>(user, "Age");
var name = Extract<string>(user, "Name");
var elapsedTimeSinceLastMessage = TimeSpan.FromTicks(Extract<long>(user, "ElapsedTimeSinceLastMessage"));
}
public static T Extract<T>(User user, string name)
{
var o = user.DataEntries
.SingleOrDefault(d => (string)d["id"] == name) // Find the one with age
.SingleOrDefault(kvp => kvp.Key != "id") // Find the not 'id' value
.Value; // Take the value
return (T)o;
}
The main issue is in the models that you created.
First of all, base on the JSON, you need another class that contains a list of Users.
public class ResultClass
{
public List<User> User { get; set; }
}
After that, because the second object of data property has not a constant name, we can't specify a constant name for it (like value). We should define the data property as an object. So the user class should be like this:
public class User
{
[JsonProperty("key")]
public string Key { get; set; }
[JsonProperty("data")]
public List<object> DataEntries { get; set; }
}
In the end, in the controller, you should deserialize the ResultJson class:
var result = JsonConvert.DeserializeObject<ResultClass>(jsonTxt);
You can use Json to C#. It generates following classes from your json string. As you can see, you can also use nullable types(long?, int?). If there is a value, sets the required variable. Otherwise leaves it as null. In this way, you can get your different type according to id of data.
public class DataEntry
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("string")]
public string String { get; set; }
[JsonProperty("timestamp")]
public long? Timestamp { get; set; }
[JsonProperty("number")]
public int? Number { get; set; }
}
public class User
{
[JsonProperty("key")]
public string Key { get; set; }
[JsonProperty("data")]
public List<DataEntry> Data { get; set; }
}
public class Root
{
public List<User> User { get; set; }
}
To Deserialize:
string response = "{\"user\":[{\"key\":\"12345678\",\"data\":[{\"id\":\"Name\",\"string\":\"Bob\"},{\"id\":\"ElapsedTimeSinceLastMessage\",\"timestamp\":1618233964000},{\"id\":\"Age\",\"number\":27}]}]}";
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(response);
what I want to do is be able to deserialize any IBaseModel and it will recursively set all IBaseModel to either Safe or Unsafe depending on what is making the call. I am currently using Newtonsoft but would be happy to switch to System.Text.Json if it will achieve the desired results.
I have the following structure:
public enum RequestPermissionType
{
Safe = 1,
Unsafe = 2,
}
public interface IBaseModel {
public long Id { get; set; }
public RequestPermissionType PermissionType { get; set; }
}
public class User : IBaseModel {
public long Id { get; set; }
public RequestPermissionType PermissionType { get; set; }
public string Name { get; set; }
public Address HomeAddress { get; set; }
}
public class Address: IBaseModel {
public long Id { get; set; }
public RequestPermissionType PermissionType { get; set; }
public string street { get; set; }
}
I tried creating a JsonConverter but I still want deserialize everything normally I just want to set either so when I override ReadJson i think it keeps calling deserialize using the same converter:
public override IBaseEntity ReadJson(JsonReader reader, Type objectType, [AllowNull] IBaseEntity existingValue, bool hasExistingValue, Newtonsoft.Json.JsonSerializer serializer)
{
var result = serializer.Deserialize<IBaseEntity >(reader);
result.PermissionType = _requestPermissionType;
return result;
}
I also tried using a converter that extended CustomCreationConverter, which works but I am trying to avoid using the activator:
public class PermissionTypeConverter : CustomCreationConverter<IBaseEntity>
{
private RequestPermissionType _requestPermissionType = RequestPermissionType.Unsafe;
public PermissionTypeConverter()
{
_requestPermissionType = RequestPermissionType.Unsafe;
}
public PermissionTypeConverter(RequestPermissionType requestPermissionType)
{
_requestPermissionType = requestPermissionType;
}
public override IBaseEntity Create(Type objectType)
{
var result = Activator.CreateInstance(objectType);
(result as IBaseEntity).PermissionType = _requestPermissionType;
return result as IBaseEntity;
}
}
Edit: Adding Json data example.
[
{
"id": 1,
"name": "User 1",
"homeAddress": {
"id": 5,
"street": "Fake Street 1"
}
},
{
"id": 2,
"name": "User 2",
"homeAddress": {
"id": 6,
"street": "Fake Street 2"
}
}
]
I have a list of items in json
"items":[
{
"id": 0,
"name": "Thats a name",
"type": 0,
"price": 3.5,
"ingredients": [1,0,2,3],
},
{
"id": 1,
"name": "This is AnotherName",
"type": 0,
"price": 3.7,
"ingredients": [5,0,6,10,2,8],
}
]
The type and ingredients properties are detailed in another object of the same JSON file. If I look it up, I know what a type 0 is, and what the ingredients are.
What I'm trying to achieve, in c#, is to have my data model not having int everywhere, but having the actual objects. For example, with the ingredients, my Item object has an Ingredients property of type List<Ingredient> and not List<int>.
Like the following :
public IEnumerable<Ingredient> Ingredients { get; set; }
public IEnumerable<FoodType> Types { get; set; }
public IEnumerable<FoodItem> Items { get; set; }
public class FoodItem
{
public int Id { get; set; }
public string Name { get; set; }
public int Type { get; set; }
public float Price { get; set; }
public IEnumerable<Ingredient> Ingredients { get; set; }
}
But in the current state of my deserialization, it crashes because it's looking for an int.
I've found keywords but not real help, about "PreserveReferenceHandling" or "isReference" but I'm not sure what those are and even less how to use them.
This is how I deserialize :
var json = r.ReadToEnd();
var items = JsonConvert.DeserializeObject<EatupDataModel>(json);
I know the following would work :
Change the json file to include actual objects and not ID's
Change data model to use int's and not objects
But I would very much like not to go that way, the first one requiring an insane amount of tedious work, and the other one forcing me to have 2 versions of pretty much the same objects, and then map the properties in between. That seems silly, surely I can't be the first person to face this.
What can I do to achieve my goal ?
You will want to clean this up a bit. But should give you a proof of concept on how to do create your custom converter.
public class Item
{
public int id { get; set; }
public string name { get; set; }
public int type { get; set; }
public double price { get; set; }
[JsonConverter(typeof(KeysJsonConverter))]
public List<Ingredient> ingredients { get; set; }
}
public class RootObject
{
public List<Item> items { get; set; }
}
public class KeysJsonConverter : JsonConverter
{
public KeysJsonConverter()
{
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException("Unnecessary because CanWrite is false. The type will skip the converter.");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var ingredientsList = new List<Ingredient>();
if (reader.TokenType != JsonToken.Null)
{
if (reader.TokenType == JsonToken.StartArray)
{
JToken token = JToken.Load(reader);
List<int> items = token.ToObject<List<int>>();
ingredientsList = items.Select(x => IngredientList.Ingredients.FirstOrDefault(y => y.Id == x)).ToList();
}
}
return ingredientsList;
}
public override bool CanRead
{
get { return true; }
}
public override bool CanWrite
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(object[]);
}
}
public static class IngredientList
{
public static List<Ingredient> Ingredients = new List<Ingredient>()
{
new Ingredient()
{
Id = 1,
Name = "Test 1"
},
new Ingredient()
{
Id = 2,
Name = "Test 2"
}
};
}
public class Ingredient{
public string Name { get; set; }
public int Id { get; set; }
}
I'm trying to parse a json string with for example [1,2,3] to an array during deserializing.
This is my json data:
[
{
"id": "1",
"district": "1",
"lon": "4.420650000000000000",
"lat": "51.21782000000000000",
"bikes": "19",
"slots": "14",
"zip": "2018",
"address": "Koningin Astridplein",
"addressNumber": null,
"nearbyStations": "3,4,5,24",
"status": "OPN",
"name": "001- Centraal Station - Astrid"
}
]
And this is my c# currently mapping to a regular string, which i would like to be an array of integers.
var AvailabilityMap = new[] { new Station() };
var data = JsonConvert.DeserializeAnonymousType(json, AvailabilityMap);
public class Station
{
public int Id { get; set; }
public double Lon { get; set; }
public double Lat { get; set; }
public int Bikes { get; set; }
public int Slots { get; set; }
public string Address { get; set; }
public string NearbyStations { get; set; }
public string Status { get; set; }
public string Name { get; set; }
}
I have found no way so far to do this in a proper way, without looping trough my current array once more..
Create a custom converter. Something like this:
public class StringToIntEnumerable : JsonConverter
{
public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}
public override bool CanWrite
{
get
{
return false; // we'll stick to read-only. If you want to be able
// to write it isn't that much harder to do.
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Note: I've skipped over a lot of error checking and trapping here
// but you might want to add some
var str = reader.Value.ToString();
return str.Split(',').Select(s => int.Parse(s));
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Now change you class to use the converter by using the JsonConverterAttribute:
public class Station
{
public int Id { get; set; }
public double Lon { get; set; }
public double Lat { get; set; }
public int Bikes { get; set; }
public int Slots { get; set; }
public string Address { get; set; }
[JsonConverter(typeof(StringToIntEnumerable))]
public IEnumerable<int> NearbyStations { get; set; } // or List<int> or int[] if
// you prefer, just make
// sure the convert returns
// the same type
public string Status { get; set; }
public string Name { get; set; }
}
And now to deserialize:
var stations = JsonConvert.DeserializeObject<List<Station>>(json);
Here is a working fiddle that uses a custom JsonConverter.
What we're doing is converting your CSV values into a proper JSON array before we convert the entire JSON string into a Station object.
Custom JsonConverter
ReadJson reads through the JSON string. First, it loads the JSON into a JObject. Next, it gets the nearbyStations property and changes it from a simple CSV string into a JavaScript array. It does this by wrapping the CSV within square brackets. Finally, we use the JsonSerializer to populate our target object and return it.
CanWrite is set to false, because this JsonConverter is only allowed to read JSON not write to JSON. As a result, we don't need to implement WriteJson. The CanConvert tests to make sure that the target object is a Station.
public class StationConverter : JsonConverter
{
public override object ReadJson(
JsonReader r, Type t, object v, JsonSerializer s)
{
JObject jObject = JObject.Load(r);
var prop = jObject.Property("nearbyStations");
var wrapped = string.Format("[{0}]", prop.Value);
JArray jsonArray = JArray.Parse(wrapped);
prop.Value = jsonArray;
var target = new Station();
s.Populate(jObject.CreateReader(), target);
return target;
}
public override void WriteJson(JsonWriter w, object v, JsonSerializer s)
{
throw new NotImplementedException("Unnecessary: CanWrite is false.");
}
public override bool CanWrite
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof (Station);
}
}
Change the Station Class to have an int[]
For the above JsonConverter to to work, change your NearbyStations property to be an int[].
public int[] NearbyStations
{
get;
set;
}
Usage Example with Live Fiddle
Here is an example of how to use it:
var AvailabilityMap =
JsonConvert.DeserializeObject<Station[]>(json, new StationConverter());
Console.WriteLine(AvailabilityMap[0].NearbyStations[0]);
The right answer is to have properly formatted input. In this case:
"nearbyStations": ["3","4","5","24"]
But I was faced with a similar situation in which the data could not be updated, so a solution had to be found. The easiest is to make a getter/setter that won't be touched by the serializer/deserializer. Unfortunately you can't ignore public properties with this serializer out of the box. So you have to do some clever work-arounds like reading into a DTO and using a business object for actual operations.
public class StationDTO
{
public int Id { get; set; }
public double Lon { get; set; }
public double Lat { get; set; }
public int Bikes { get; set; }
public int Slots { get; set; }
public string Address { get; set; }
public string NearbyStations { get; set; }
public string Status { get; set; }
public string Name { get; set; }
}
...
public class Station : StationDTO
{
public List<string> NearbyStationsList
{
get
{
return NearbyStations.Split(',');
}
set
{
NearbyStations = string.Join(",", value);
}
}
}
More information: Newtonsoft ignore attributes?