Using JsonProperty for Deserializing but NOT serializing [duplicate] - c#

This question already has answers here:
How to ignore JsonProperty(PropertyName = "someName") when serializing json?
(2 answers)
Closed 3 years ago.
I have a backend-service that calls a REST-Api. The result of that API is then deserialized into my entity:
public class Item {
[JsonProperty("pkID")]
public int Id {get;set;}
}
JsonConvert.DeserializeObject<Item>(responseString);
This works fine. But I also want to return the result as a JSON-string so I can use it from the Frontend. When now Serializing my object of Type "Item" using JsonConvert.SerializeObject(item) I want to return something like
{ Id: 1 }
Instead on serializing it also uses the JsonProperty and returns
{ pkID: 1 }
instead.
How can I tell the serializer to ignore the JsonProperty on serializing, but use it on deserializing?
I am NOT searching for a way whether the property should be serialized or not, but whether the propertyName should be used or the the name from the JsonProperty on serializing.

You could use a set-only property that points to the 'good' property.
public class Item
{
public int Id { get; set; }
[JsonProperty("pkID")]
public int BackwardCompatibleId { set => Id = value; }
}
// test
var x = new Item { Id = 88 };
var json = JsonConvert.SerializeObject(x); // {"Id":88}
var clone = JsonConvert.DeserializeObject<Item>("{\"pkId\":99}");

you could use an own implementation of the ContractResolver.
here is an answer that could probably work: https://stackoverflow.com/a/20639697/5018895

Related

Skip serializing a list element if a condition is satisfied (Newtonsoft) [duplicate]

This question already has answers here:
Excluding specific items in a collection when serializing to JSON
(3 answers)
Closed 3 years ago.
I am using Newtonsoft for serialization and I want to skip serializing a specific element in a list.
Say, I have a class:
public class Car
{
public PropertyA A {get; set;}
public PropertyB B {get; set;}
public bool ShouldSerializeCar {get; set;}
}
And I have an Action method that returns a List<Car> as a reponse like:
[HttpGet("cars", Name = "GetCars")]
[ProducesResponseType(typeof(IEnumerable<Car>), 200)]
public async Task<IActionResult> GetCars()
{
var cars = new List<Car>();
//Some code here that generates a list of Car//
return cars;
}
When Newtonsoft serializes the response, is it possible to skip serializing list items where ShouldSerializeCar is false?
Please note that I cannot use another library except Newtonsoft as it has been used all over the project.
Instead of relying on Newtonsoft to do this why would you not filter your list before serializing your list?
code:
[HttpGet("cars", Name = "GetCars")]
[ProducesResponseType(typeof(IEnumerable<Car>), 200)]
public async Task<IActionResult> GetCars()
{
var cars = _repo.GetCars().Where(c => c.ShouldSerializeCar );
retur Ok(cars);
}

Serialize and deserialize a hierarchy of a C# class to Json [duplicate]

This question already has answers here:
Using Json.NET converters to deserialize properties
(9 answers)
Closed 6 years ago.
Is there a way to serialize and then deserialize a class that has a member variable of unknown type that could be either be a simple value type or an instance of the containing class itself ?
public class A
{
public dynamic Value { get; set; }//Value could be int or type A for example
}
public static class ASerializer
{
public static string ToJson(A table)
{
return JsonConvert.SerializeObject(table);//using Json.Net
}
public static A FromJson(string json)
{
return JsonConvert.DeserializeObject<A>(json);
}
}
public class Tests
{
public static void TestASerialization()
{
var a = new A() { Value = 1 };
var aa = new A { Value = a };
var aaa = new A { Value = aa };
var json = ASerializer.ToJson(aaa);
var aaa2 = ASerializer.FromJson(json);
var aa2 = (A)aaa2.Value; //throws
}
}
if I serialize and then deserialize aaa - I can't cast the Value of the deserialized aaa back to type A I get:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : Cannot convert type 'Newtonsoft.Json.Linq.JObject' to
'A'
Any suggestions on handling this nested hierarchy elegantly, without resorting to hand coding ?
Seems to work with just one instance of A with Value of type A.
You aren't casting what you think you're casting.
In this case, you're actually casting the Value property to A. You need to wrap the aaa2 instance in params with the cast before accessing the property.
var aa2 = ((A)aaa2).Value;
Dynamic is a compiler hack mostly, I would recommend generics instead.
#David L 's answer is also correct.
public class A<T>
{
public T Value { get; set; }
}

Conditionally deserialize JSON string or array property to C# object using JSON.NET? [duplicate]

This question already has answers here:
How to handle both a single item and an array for the same property using JSON.net
(9 answers)
Closed 6 years ago.
I have a defined C# object based off a very complex JSON I'm getting from a third party API. Here's a piece of it:
{"alarmSummary":"NONE"}
The corresponding property in C# would be:
public string alarmSummary {get; set;}
And I would get this converted by using my typical JSONConvert from JSON.NET:
var alarms = JSONConvert.DeserializeObject<MyClass>(jsonString);
However, the API will put alarms in this format, as an array, and "NONE" when there aren't any as a string:
{"alarmSummary" : ["AHHH Something went wrong!!", "I'm on fire!!"]}
Which means in C# it would need to be:
public string[] alarmSummary {get; set;}
If I could, I would just have the JSONConvert deserialize the "NONE" string into an array of just one entry. Is there a way to set conditions on this property, or will I have to take the whole complex JSON string and hand convert it?
This one should be easy - you can set your alarmSummary as object and then have separate property that evaluates alarmSummary and returns null or array depending on the value.
public object alarmSummary { get; set; }
protected string[] alarmSummaryCasted
{
get
{
if (alarmSummary is String)
return null;
else
return (string[]) alarmSummary;
}
}
If you are expecting only those two combinations, you could make use of the dynamic keyword and check deserialized object:
string json = "{\"alarmSummary\":\"NONE\"}";
//string json = "{\"alarmSummary\" : [\"AHHH Something went wrong!!\", \"I'm on fire!!\"]}";
string[] alarmSummary;
dynamic obj = JsonConvert.DeserializeObject(json);
if (obj.alarmSummary.Type == JTokenType.Array)
alarmSummary = obj.alarmSummary.ToObject<string[]>();
else
alarmSummary = new[] { (string)obj.alarmSummary.ToObject<string>() };

Determining object "type" during json deserialization

While trying to de-serialize a complex JSON object (JIRA issue) into an object containing a dictionary of type string-Field I've hit a bit of a bump.
While I can de-serialize various pre-determined object types (standard), I'm having a bit of a harder time with the custom fields, which could be of various types (they all begin with customfield_ followed by a set of numbers).
The custom fields can be floats, strings, booleans, objects and arrays of objects. The latter of these is causing me issues since I can't seem to determine what the object is before I de-serialize it.
I've searched for a way to perhaps "peek" at the data in the object before de-serializing as one of the fields contains information specific to it's type. This is all so I can determine the type of the object and tell Json.Net what to de-serialize it as.
I've considered parsing the JSON string before serialization to get the information, or maybe just when hitting this particular case, but maybe there is a better way?
Thanks in advance for any advice on this.
You can deserialize to an object with Json.Net. Here's a quick and dirty example:
using System;
using Newtonsoft.Json;
namespace Sandbox
{
class Program
{
private static void Main(string[] args)
{
var nestDto = new Dto
{
customfield_1 = 20,
customfield_2 = "Test2"
};
var dto = new Dto
{
customfield_1 = 10,
customfield_3 = new[] { nestDto },
customfield_2 = "Test"
};
var jsonString = JsonConvert.SerializeObject(dto);
Console.WriteLine(jsonString);
var fromJsonString = JsonConvert.DeserializeObject<Dto>(jsonString);
Console.WriteLine(fromJsonString.customfield_3[0].customfield_2); //Outputs Test2
Console.ReadKey();
}
}
class Dto
{
public int customfield_1 { get; set; }
public string customfield_2 { get; set; }
public Dto[] customfield_3 { get; set; }
}
}
Instead of peaking, you can deserialize as the same type as JSON.net uses for ExtensionData explicitly. For example:
if (reader.TokenType == JsonToken.StartArray)
{
var values = serializer.Deserialize<List<Dictionary<string, JToken>>>(reader);
objectContainer = ClassifyAndReturn(values);
}
private ObjectType ClassifyAndReturn(List<Dictionary<string, JToken>> values)
{
if (values.First().ContainsKey("self"))
{
string self = values.First()["self"].Value<string>();
if (self.Contains("customFieldOption"))
//... Then go into a series of if else cases to determine the object.
The representation of the objects are given as a Dictionary of string to JToken, which can then easily be checked and assigned manually or in some cases automatically deserialized (in the case one of the fields is another object).
Here is what an object constructor could look like:
internal myobject(Dictionary<string, JToken> source)
{
Self = source["self"].Value<string>();
Id = source["id"].Value<string>();
Value = source["value"].Value<string>();
}

Deserialization of get only properties in C# using json.net / webapi [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Using Json.net - partial custom serialization of a c# object
I have a class that I successfully get to serialize in json.net when using asp.net MVC 4 WebAPI. The class has a property that is a list of strings.
public class FruitBasket {
[DataMember]
public List<string> FruitList { get; set; }
public int FruitCount {
get {
return FruitList.Count();
}
}
}
In my Get method the serialization happens ok and I get an empty array i.e. [] for the FruitList property in my JSON. If I use the same json in a PUT request's body I get an error in the FruitCount property during deserialization because FruitList is null.
I want the FruitList property (basically my get only properties) to serialize but not deserialize. Is it possible with a setting or other wise with json.net?
I realize this does not answer your question, but addresses the error being generated so might make worrying about custom serialization irrelevant
use a private variable for FruitList, return it in the get and in set, if value is null then set the private variable equal to a new list.
public class FruitBasket
{
private List<string> _fruitList;
[DataMember]
public List<string> FruitList
{
get
{
return _fruitList;
}
set
{
if (value == null)
{
_fruitList = new List<string>();
}
else
{
_fruitList = value;
}
}
}
public int FruitCount
{
get
{
return FruitList.Count();
}
}
}

Categories