robsonrosa robsonrosa - 2 months ago 32
JSON Question

Unity3D post a json to ASP.NET MVC 4 Web Api

How I do a post with json value to a ASP.NET MVC 4 Web Api Controller?
I tried it several ways, but I can't make it works.

First, my simplified Controller action:

public Interaction Post(Interaction filter)
return filter;

And my post method with Unity3D WWW:

public string GetJson(string url, WWWForm form)
var www = new WWW(url, form);

while (!www.isDone) { };

return www.text;

Where my WWWForm is:

var form = new WWWForm();
form.AddField("filter", interaction);

I tried specify the header, like:

public string GetJson(string url, byte[] data)
var header = new Hashtable();
header.Add("Content-Type", "text/json");

var www = new WWW(url, data, header);

while (!www.isDone) { };

return www.text;

I really tried to solve this by more than ten different ways and I always get the same result:

Debug.Log(input); // {"Id":15,"Name":"Teste","Description":"Teste","Value":0.0,"Time":10.0}
Debug.Log(output); // {"Id":0,"Name":null,"Description":null,"Value":0.0,"Time":0.0}

Any direction will be helpful. Thanks!


Do not use WWWForm to post JSON. Use something like this.

string input = "You JSON goes here";

Hashtable headers = new Hashtable();
headers.Add("Content-Type", "application/json");

byte[] body = Encoding.UTF8.GetBytes(input);

WWW www = new WWW("http://yourserver/path", body, headers);

yield www;

if(www.error) {
else {

Assuming JSON string in input is like this,


you will need a class like this

public class Interaction
   public int Id { get; set; }
   public string Name { get; set; }
   public string Description { get; set; }
   public string Teste { get; set; }
   // other properties

for the action method like this to work

public Interaction Post(Interaction filter)