I want to convert my below nested request to Query String
var parameter = new RulesCommandServiceAppendRequest()
{
Chain = Chain.INPUT,
Data = new RuleInputModel()
{
Protocol = "tcp",
SourceIp = "2.2.2.2",
DestinationIp = "1.1.1.1",
SourcePort = "111",
DestinationPort = "222",
Jump = "DROP"
}
};
to something like below
Chain=INPUT&Data.DestinationIp=1.1.1.1&Data.DestinationPort=222&Data.Jump=DROP&Data.Protocol=tcp&Data.SourceIp=2.2.2.2&Data.SourcePort=111
WebSerializer workaround
I try with WebSerializer library with call WebSerializer.ToQueryString(parameter)
I see below output:
Chain=INPUT&Data=DestinationIp=1.1.1.1&DestinationPort=222&Jump=DROP&Protocol=tcp&SourceIp=2.2.2.2&SourcePort=111"
As you can see, the output is not as expected and my ASP.NET WebApi .NET6 sample server does not accept this. (for more info you can see https://github.com/BSVN/IpTables.Api/pull/18)
Did you know another library for doing this or some trick to correct using WebSerializer
?
3
Answers
try this :
Well, if you look for the answer other than using the
WebSerializer
way,Implement the
DataContract
attribute seems the quickest, but I highly doubt next time if you want to convert theRuleInputModel
instance only to query string or if you have other models with the property withRuleInputModel
type (but different name), it will result in the query param name will have the "Data." prefix.Thus, recommend writing a custom implementation for it. For this case, the expected result is flattened JSON and then converted to a query string.
You can use the Newtonsoft.Json library to achieve the JSON flattening, converting an object to
Dictionary<string, object>
type, credit to the GuruStron’s answer on Generically Flatten Json using c#.For the second method will be converting the
Dictionary<string, object>
to query string.The minor change in your
RulesCommandServiceAppendRequest
class which you want to serialize theChain
value as string instead of integer.Caller method:
I got it to work using
WebSerializerAnnotation
:Fiddle : https://dotnetfiddle.net/h28gKx
Output: