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.

3
  • 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 Commented Mar 5, 2018 at 13:13
  • o.O ok, Ive deleted the comment... Anyways, he said "use [JsonIgnore] attribute" (in your Info property) Commented Mar 5, 2018 at 13:14
  • Possible duplicate of Json.NET serialize property on the same level Commented Mar 5, 2018 at 13:19

1 Answer 1

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_"
}
Sign up to request clarification or add additional context in comments.

4 Comments

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 Will it be possible to update your question and show exactly how you want the JSON to look like?
@Tecno see my updated answer and let me know if it is useful?
Thanks for suggestion, i think this is what i need: stackoverflow.com/questions/18658955/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.