I'm querying an API, the response is a custom JSON. After looking over the web, I managed to deserialize it into a custom object this way:
Post.cs
[JsonConverter(typeof(JsonPathConverter))]
public class Post
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "taken_at_timestamp")]
public long Timestamp { get; set; }
[JsonProperty(PropertyName = "edge_media_preview_like.count")]
public int LikeCount { get; set; }
[JsonProperty(PropertyName = "edge_media_to_comment.count")]
public int CommentCount { get; set; }
[JsonProperty(PropertyName = "edge_media_to_caption.edges[0].node.text")]
public string Caption { get; set; }
[JsonProperty(PropertyName = "display_url")]
public string Image { get; set; }
[JsonProperty(PropertyName = "dimensions.width")]
public int Width { get; set; }
[JsonProperty(PropertyName = "dimensions.height")]
public int Height { get; set; }
[JsonProperty(PropertyName = "shortcode")]
public string Shortcode { get; set; }
}
JsonPathConverter.cs
public class JsonPathConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
object targetObj = Activator.CreateInstance(objectType);
foreach (PropertyInfo prop in objectType.GetProperties().Where(p => p.CanRead && p.CanWrite))
{
JsonPropertyAttribute att = prop.GetCustomAttributes(true)
.OfType<JsonPropertyAttribute>()
.FirstOrDefault();
string jsonPath = (att != null ? att.PropertyName : prop.Name);
JToken token = jo.SelectToken(jsonPath);
if (token != null && token.Type != JTokenType.Null)
{
object value = token.ToObject(prop.PropertyType, serializer);
prop.SetValue(targetObj, value, null);
}
}
return targetObj;
}
public override bool CanConvert(Type objectType)
{
return false;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
The problem is when I want to send that object as a JSON: It returns fields with PropertyName value, instead of attribute name:
[
{
"id": "2322829435103312153",
"taken_at_timestamp": 1591122868,
"edge_media_preview_like.count": 24,
"edge_media_to_comment.count": 0,
"edge_media_to_caption.edges[0].node.text": "...",
"display_url": "...",
"dimensions.width": 1080,
"dimensions.height": 1080,
"shortcode": "..."
}
...
]
Is there a way to use PropertyName for deserialize but attribute name for serialize?
UPDATE
As requested, this is how I use deserialization and serialization:
Deserialize
JArray response = "[{ ... }]";
List<Post> posts = new List<Post>();
foreach (JObject node in response)
{
Post post = JsonConvert.DeserializeObject<Post>(node.ToString());
posts.Add(post);
}
Serialize
I just return the List inside an "Ok" IActionResult:
Ok(posts);