将存储在字符串中的Json值分配给类值,然后存储在SQL中

时间:2016-11-04 09:11:27

标签: c# json

我从网站收到JSON对象并将其存储在字符串值中。我已经生成了映射到JSON obejct的必要类。我的问题是如何将JSON的值赋给类属性/ variables

JSON数据:

{
    "echo_req": {
        "subscribe": 1,
        "transaction": 1
    },
    "msg_type": "transaction",
    "transaction": {
        "action": "buy",
        "amount": "-250.0000",
        "balance": "530800.61",
        "contract_id": "108 32430388",
        "currency": "USD",
        "date_expiry": 1478242335,
        " display_name": "Volatility 10 Index",
        "id": "de7cc6e6-218c-86a5-805f-093c1176f605",
        "longcode": "Win payout if Volatility 10 Index is strictly lower than entry spot at 15 minutes after contract start time.",
        "symbol": "R_10",
        "transaction_id": "215802164 88",
        "transaction_time": 1478241435
    }
}

C#class:

namespace BinaryData
 {

    public class Echo_Req
    {
        public int subscribe { get; set; }
        public int transaction { get; set; }
    }
    public class Transaction
    {
        public string action { get; set; }
        public string amount { get; set; }
        public string balance { get; set; }
        public string contract_id { get; set; }
        public string currency { get; set; }
        public int date_expiry { get; set; }
        public string display_name { get; set; }
        public string id { get; set; }
        public string longcode { get; set; }
        public string symbol { get; set; }
        public string transaction_id { get; set; }
        public int transaction_time { get; set; }
    }

    public class Rootobject
    {
        public Echo_Req echo_req { get; set; }
        public string msg_type { get; set; }
        public Transaction transaction { get; set; }
    }

}

在程序中,我遇到了如何分配合同ID

var str = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);//
Console.WriteLine(str);//prints json correctly

Transaction tradeDetails = new Transaction();
tradeDetails.contract_id=str.contract_id//How do I do this

另外只是旁注,这是获取值来编写存储在SQL中的代码的有效方法。我将使用ADO.NET因为根本就不知道EF

1 个答案:

答案 0 :(得分:0)

您需要使用JSON.NET将JSON字符串反序列化为对象。

在你的情况下:

Rootobject ro = JsonConvert.DeserializeObject<Rootobject>(str);

然后

tradeDetails.contract_id = ro.transaction.contract_id 

在你的JSON中是小故障

" display_name" - 应为"display_name" - 我认为这是拼写错误。