Overwrite Json data toString() function to make www-form-urlencoded string

  • Thread starter Thread starter zydjohn
  • Start date Start date
Z

zydjohn

Guest
Hello:

I have to use HTTP client to post some x-www-form-urlencoded string to a web server.

The issue is the x-www-form-urlencoded formatted string is very very long, so I want to create a class to make it, and override the default toString() to build the string, so it can be posted to the web server.

For a short example of the x-www-form-urlencoded formatted string, it is something like this:

header0-A=1&header0-B=2&header0-C=3&timestamp=1579815039620

The header0 is something like this:

data-874969c24397b26ea55d9ec3e118096ea80a122e

What I want to do is something like this:


publicclassUrlencoded_Data

{

publicstringHeader0{ get; set; }

publicdecimalData1{ get; set; }

publicdecimalData2{ get; set; }

publicdecimalData3{ get; set; }

publiclongtimestamp{ get; set; }

publicoverridestringToString()

{

returnJsonSerializer.Serialize(this);

}

}


I want to write one statement like this:

Urlencoded_Data pay_load1 = newUrlencoded_Data

{

Header0 = @"data-874969c24397b26ea55d9ec3e118096ea80a122e",

Data1 = 1m,

Data2 = 2m,

Data3 = 3m,

TimeStamp = 123456,

};

stringpost_data = pay_load1.ToString();

Comparing to the string I need for posting to web server, which is a string like this:

data-874969c24397b26ea55d9ec3e118096ea80a122e-A=1&data-874969c24397b26ea55d9ec3e118096ea80a122e-B=2&data-874969c24397b26ea55d9ec3e118096ea80a122e-C=3&timestamp=1579815039620

I got the Json string like this:

{"data-874969c24397b26ea55d9ec3e118096ea80a122e":"data-874969c24397b26ea55d9ec3e118096ea80a122e","Data1":1,"Data2":2,"Data3":3,"timestamp":123456}

They are totally different, I know I can use something like this:

string post_data =

string.Format("{0}-A={1}&{0}-B={2}&{0}-C={3}&timestamp={4}", @"data-874969c24397b26ea55d9ec3e118096ea80a122e", 1, 2, 3, 1579815039620);

Even the code works, but it looks ugly, I want to know if I can overwrite the toString() function, so it can do the job as the string.Format does.

Thanks,

Continue reading...
 
Back
Top