0

I have the below properties of an object:

public string SenderAccount { get; set; }
public string ReceiverAccount { get; set; }
public decimal Amount { get; set; }
public string Currency { get; set; }
public Info Info { get; set; }

And I want to have an output like this:

{ "sender_account":"1753154", 
  "receiver_account":"1753242",
  "amount":15,
  "currency":"USD",
  "test":1, 
  "key":"_MERCHANT_KEY_",
  "ts":_TIMESTAMP_, 
  "sign":"_SIGN_" 
}

Where test,key,ts and sign, belong to Info object. Now I want to skip this part:

1."Info":
2.{
3.     "test":0,
4.     "key":"mkey",
5.     "ts":time_stamp,
6.     "sign":"signature"
7.}

But to output only Info variables. Reason is that from api documentation provided they use all time those Info variables to request.

Edit: I need to skip rows 1,2,7 during serialization.

Tecno
  • 65
  • 1
  • 7
  • Complementing the comment by @Ive, you will also need to create properties in your base class to return Info's Test, Key and Ts properties – Mari Faleiros Mar 05 '18 at 13:13
  • o.O ok, Ive deleted the comment... Anyways, he said "use [JsonIgnore] attribute" (in your Info property) – Mari Faleiros Mar 05 '18 at 13:14
  • Possible duplicate of [Json.NET serialize property on the same level](https://stackoverflow.com/questions/18658955/json-net-serialize-property-on-the-same-level) – Ive Mar 05 '18 at 13:19

1 Answers1

1

You can do it like:

Object1 object1 = new Object1
{
    sender_account = "1753154",
    receiver_account = "1753242",
    amount = 15,
    currency = "USD",
    Info = new Info
    {
        test = 1,
        key = "_MERCHANT_KEY_",
        ts = "_TIMESTAMP_",
        sign = "_SIGN_"
    }
};

And serialize it like:

var resultJson = JsonConvert.SerializeObject(new
{
    object1.sender_account,
    object1.receiver_account,
    object1.amount,
    object1.currency,
    object1.Info.test,
    object1.Info.key,
    object1.Info.ts,
    object1.Info.sign,
});

Output:

{
    "sender_account": "1753154",
    "receiver_account": "1753242",
    "amount": 15,
    "currency": "USD",
    "test": 1,
    "key": "_MERCHANT_KEY_",
    "ts": "_TIMESTAMP_",
    "sign": "_SIGN_"
}
FaizanHussainRabbani
  • 3,256
  • 3
  • 26
  • 46
  • The point is that i want to keep in same object (object1 to have an instance of object2 and during serialization to skip *Object2 {...}* ), as *Info* will be used everywhere, in all API requests. Edit: Object2 name, so in output will be only its variables – Tecno Mar 05 '18 at 14:24
  • @Tecno Will it be possible to update your question and show exactly how you want the JSON to look like? – FaizanHussainRabbani Mar 05 '18 at 14:25
  • @Tecno see my updated answer and let me know if it is useful? – FaizanHussainRabbani Mar 05 '18 at 14:34
  • Thanks for suggestion, i think this is what i need: https://stackoverflow.com/questions/18658955/json-net-serialize-property-on-the-same-level – Tecno Mar 05 '18 at 14:36