Reputation: 321
I have a post request being sent to my RESTful API in the following format
Headers
Host: localhost:9475
Expect: 100-continue
Content-Type: application/json
Content-Length: 59
Body
{"query":"SOME STRING","variables":{"Foo":{"Data":"ABCD"}}}
I'm trying to receive the data in the body of the request, so this is what i've tried:
public void foo(string query, object variables)
The query parameter is being parsed correctly but the variables parameter always gets {object}
as its value.
public void foo(string query, Dictionary<string, object> variables)
The query parameter is being parsed correctly but the variables parameter is a dictionary with no keys/values.
public void foo(string query, VariablesObj variables)
where VariablesObj
public class VariablesObj
{
public object input_0 {get; set;}
}
The query parameter is being parsed correctly and the variables parameter has one property input_0 with the value of {object}
.
Am i doing something wrong? or am i missing something that i need to implement for this to work.
Edit 1:
I tried @rene's answer and it worked for this scenario, but my problem now is that the object inside Foo
is not always the same as i'm using GraphQl with Relay on the client side and it changes the variables to whatever object it needs to send but it's usually just one object inside.
Upvotes: 2
Views: 491
Reputation: 42414
To get a proper mapping make sure you have a class with a public property Foo which is of a type that has a public property Data of type string.
If this is your public interface
public void foo(string query, MyVars variables)
you'll need the following classes:
public class MyVars
{
public DataVars Foo { get; set; }
}
public class DataVars
{
public string Data { get; set;}
}
You can quickly test this with the DataContractJsonSerializer:
var json = @"{""query"":""SOME STRING"",""variables"":{""Foo"":{""Data"":""ABCD""}}}";
var ser = new DataContractJsonSerializer(typeof(wrapper));
var sr = new MemoryStream(Encoding.UTF8.GetBytes(json));
var mv = (wrapper) ser.ReadObject(sr);
mv.Dump();
I add one extra wrapper type as a stand-in for the the method signature:
public class wrapper
{
public string query {get; set;}
public MyVars variables { get;set;}
}
When run in LinqPad this will be the result:
Which proves that our class hierarchy is correct to fully deserialize the given Json.
When your variables can be of all kind of data shapes you have to define as much class as you need to cover those and supply them on the specialized constructor that takes a list of knowntypes: DataContractJsonSerializer Constructor (Type, IEnumerable<Type>)
. The process to make design those classes doesn't change, you'll only have a bunch of them. Add the KnownType
attribute to your datacontract classes.
Upvotes: 2