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

本文关键字:存储 然后 SQL Json 字符串 分配 | 更新日期: 2023-09-27 18:16:39

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

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#类:

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。因为还不知道EF

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

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

In Your case:

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

tradeDetails.contract_id = ro.transaction.contract_id 

JSON中是glitch

" display_name" -应该是"display_name" -我想这是打字错误

相关文章: