值为c#中的json字符串 [英] Values frm a json string in c#

查看:66
本文介绍了值为c#中的json字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using System;
using System.Net;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;



public partial class Food1 : System.Web.UI.Page
{
    string selectSQL;

    SqlCommand cmd = new SqlCommand();
     SqlCommand cmd1 = new SqlCommand();
    SqlConnection dbConn = new SqlConnection();
    SqlConnection dbConn1 = new SqlConnection();
    SqlConnection dbConn2 = new SqlConnection();
    SqlConnection dbConn3 = new SqlConnection();
    SqlConnection dbConn4 = new SqlConnection();
    SqlDataReader dr;
    public string dbstring = WebConfigurationManager.ConnectionStrings["DB_SCH"].ConnectionString;
    public SqlConnection MyConnection, MyConnection1;

    Stream st;

   protected void Page_Load(object sender, EventArgs e)
    {

string url ="https://stageserv.interswitchng.com/test_paydirect/api/v1/gettransaction.json?";
    productid.Value= "6205";

      transactionreference.Value = "7654325";
       
      amount.Value = "16700000";

      string mac =  "D3D1D05AFE42AD50818167EAC73C109168A0F108F32645C8B59E897FA930DA44F9230910DAC9E20641823799A107A02068F7BC0F4CC41D2952E249552255710F";
       
           // https://stageserv.interswitchng.com/test_paydirect/api/v1/gettransaction.json?productid=6205&transactionreference=1234567&amount=3000000 
//string ss ="https://stageserv.interswitchng.com/test_paydirect/api/v1/gettransaction.json?productid=21&transactionreference=8421941122&amount=300000";
//string ft =  "username=" + amount.Value+"&"+"username=" + amount.Value;
string now = url+"productid=" + productid.Value+"&"+"transactionreference=" + transactionreference.Value+"&"+"amount=" + amount.Value;


//Product_id.Value=(Convert.ToString(productid.Value)).ToString()+(Convert.ToString(transactionreference.Value)).ToString()+(Convert.ToString(amount.Value)).ToString();
string m_Input =(Convert.ToString(productid.Value)).ToString()+(Convert.ToString(transactionreference.Value)).ToString()+mac;

 


  Session["u"] = now;
//Response.Write(m_Input);
// Convert a string to byte
byte[] data = Encoding.UTF8.GetBytes(m_Input );
byte[] hash;
SHA512 shaM = new SHA512Managed();
 
// Convert byte to SHA512
hash = shaM.ComputeHash(data);
 
 
// Append bytes
StringBuilder result = new StringBuilder(hash.Length * 2);
for (int i = 0; i < hash.Length; i++)
result.Append(hash[i].ToString(false ? "X2" : "x2"));
 


Session["rr"] =result;
Response.Write(result+"<hr>");
//string bs = (Convert.ToString(Session["rr"])).ToString();

     
  
 
     }
protected void Button2_Click(object sender, EventArgs e)
    {

        Response.Write("URL <hr>"+Session["u"].ToString());

        try
        {
            var request = (HttpWebRequest)WebRequest.Create(Session["u"].ToString());
            request.Headers.Add("Hash", Session["rr"].ToString());
            var response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();

            Response.Write("<br>Result<br>" + responseFromServer.ToString() + "<br>Result<br>");
        }
        catch (Exception et)
        {
            Response.Write("Error "+et.ToString());
        }
        

    }
} 







我得到的回复是






The response i get is

{"Amount":16700000,"CardNumber":"0095","MerchantReference":"7654325","PaymentReference":"FBN|WEB|WEBP|3-02-2016|170619","RetrievalReferenceNumber":"000000088836","LeadBankCbnCode":null,"LeadBankName":null,"SplitAccounts":[],"TransactionDate":"2016-02-03T16:41:43.923","ResponseCode":"00","ResponseDescription":"Approved Successful"}







我如何获得交易日期,ResponseDescription和交易日期的值c sharp,请我需要代码



我尝试了什么:



值来自C#中的JSON字符串




how do i get the values of Transaction Date,ResponseDescription and Transaction date in c sharp ,please i need the code

What I have tried:

values frm a JSON string in C#

推荐答案

1 - Download the Newtonsoft JSON DLL (or set up a Nuget fetch)
2 - Add the reference to your project
3 - Create a class (Transaction) with properties that match the names of the JSON fields.

Conversion becomes:

Transaction t = Json.JsonConvert.DeserializeObject<Transaction>(the JSON string)

Examples and more detail on Newtonoft's site.





反序列化对象 [ ^ ]



回应不理解的评论。





1 - 。 Net框架(还)没有一个库,它提供了从JSON字符串到C#对象的轻松转换。

2 - Newtonsoft(按照上面的链接到网站并且已经找到了)提供了一个DLL(库) 。它可以免费下载。下载它。获取正在使用的.Net版本的正确版本。

3 - 在项目中添加对Newtonsoft DLL的引用,如果您不知道如何执行此操作,请参阅MSDN。 br />


使用它:



我们只需要你的JSON字符串中的前几个字段来制作示例简单。





Deserialize an Object[^]

In response to "don't understand" comment.


1 - The .Net framework doesn't (yet) have a library that provides easy translation from JSON string to C# object.
2 - Newtonsoft (follow link above to website and have poke around) provide a DLL (library). It is free to download. Download it. Get the right version for the version of .Net that you are using.
3 - Add a reference to the Newtonsoft DLL to your project, see MSDN if you don't know how to do this.

To use it:

We'll take just the first few fields in your JSON string to make the example simple.

{'Amount':16700000,'CardNumber':'0095','MerchantReference':'7654325'}





创建一个具有与名称匹配的属性的事务(或您选择的任何其他名称)你的JSON字符串中的字段。





Create a class Transaction (or any other name that you choose) that has properties that match the names of the fields in your JSON string.

Class Transaction {
  Public Long Amount {get; set;}
  Public String CardNumber {get; set;}
  Public String MerchantReference {get; set;}
}



转换的代码是......




And the code to convert is...

String json = @"{'Amount':16700000,'CardNumber':'0095','MerchantReference':'7654325'}";
Transaction t = Json.JsonConvert.DeserializeObject<Transaction>(json);





交易对象t将具有你想要的价值。





And the transaction object t will have the values you want.

Console.WriteLine(t.CardNumber);
Console.WriteLine(t.Amount);
Console.WriteLine(t.MerchantReference);


公共类帮助

{

public int Amount {get;组; }

公共对象CardNumber {get;组; }







}



String json = responseFromServer.ToString();

帮助h = Json.JsonConvert.DeserializeObject< help>(json);



控制台。的WriteLine(h.CardNumber); - 此行错误

无效的令牌'('在类,结构或接口成员声明中
public class Help
{
public int Amount { get; set; }
public object CardNumber { get; set; }



}

String json = responseFromServer.ToString();
Help h = Json.JsonConvert.DeserializeObject<help>(json);

Console.WriteLine(h.CardNumber); - error on this line
Invalid token '(' in class, struct, or interface member declaration

这篇关于值为c#中的json字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆