在Json序列化期间是否可以跳过对象名称?

时间:2018-03-05 13:08:22

标签: c# json.net json-serialization

我有一个对象的以下属性:

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; }

我希望得到这样的输出:

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

test,key,ts和sign 属于Info对象。 现在我想跳过这一部分:

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

但是只输出Info个变量。 原因是,从api文档提供了他们所有时间使用这些Info变量来请求。

编辑:我需要在序列化期间跳过第1,2,7行。

1 个答案:

答案 0 :(得分:1)

你可以这样做:

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_"
    }
};

并将其序列化为:

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,
});

<强>输出:

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