C
C#3y ago
Dasic

Newtonsoft.Json deserialize issue [Answered]

I have a json string. For example this one:
{"type":"accept","id":0,"ms_id":"00000","user_id":"000000000000","item_name":"Test Item","acc_name":"account"}
{"type":"accept","id":0,"ms_id":"00000","user_id":"000000000000","item_name":"Test Item","acc_name":"account"}
How can I deserialize some fields to a structure field in my class? For instance:
public class Order
{
[JsonProperty("id")] public int Id { get; init; }
[JsonProperty("item_name")] public string ItemName { get; init; }

[JsonProperty("ms_id")] public long MessageId { get; init; }

public Account Account { get; init; }
}

public struct Account
{
[JsonProperty("user_id")] public long UserId { get; init; }
[JsonProperty("acc_name")] public long Nickname { get; init; }
}
public class Order
{
[JsonProperty("id")] public int Id { get; init; }
[JsonProperty("item_name")] public string ItemName { get; init; }

[JsonProperty("ms_id")] public long MessageId { get; init; }

public Account Account { get; init; }
}

public struct Account
{
[JsonProperty("user_id")] public long UserId { get; init; }
[JsonProperty("acc_name")] public long Nickname { get; init; }
}
How can I deserialize the string to put these two fields in an Account field?
6 Replies
Yawnder
Yawnder3y ago
jcotton42
jcotton423y ago
afaik neither Newtonsoft, nor System.Text.Json can do what you want direclty
Yawnder
Yawnder3y ago
What I would do is have the input model flat, then transform it to your DTO manually rather than making a custom converter. (if you have no control over the input string, that is.)
Dasic
DasicOP3y ago
Okay, thank you so much for answers
Yawnder
Yawnder3y ago
It's not about structs. It's about the target class not having the same structure than the source. (Source has A, B, C, and the target class has A, D while D contains B, C.)
Accord
Accord3y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server