Daniel Eugen
Daniel Eugen

Reputation: 2780

Send JSON Object with HttpClient in C#

Well, I know that HttpClient.SendAsync() can be used to send HttpRequestMessage and request Method can be set to POST and Content to StringContent for simple string... but in my case i want to send a more complex JSON string which looks like this

{
  "requests": [
    {
      "image": {
        "content": ""
      },
      "features": [
        {
          "type": "UNSPECIFIED",
          "maxResults": 50
        }
      ]
    }
  ]
}

I tried to use JavaScriptSerializer but don't know how to create an object that reprsents such json.

await Browser.SendAsync(new HttpRequestMessage
{
    RequestUri = new Uri("http://127.0.0.1/"),
    Method = HttpMethod.Post,
    Content = new StringContent(new JavaScriptSerializer().Serialize())
});

Upvotes: 0

Views: 977

Answers (2)

David Colwell
David Colwell

Reputation: 2590

If you want the C# code for this object, use the RootObject class

public class Image
{
    public string content { get; set; }
}

public class Feature
{
    public string type { get; set; }
    public int maxResults { get; set; }
}

public class Request
{
    public Image image { get; set; }
    public List<Feature> features { get; set; }
}

public class RootObject
{
    public List<Request> requests { get; set; }
}

Provided courtesy of http://json2csharp.com/

Upvotes: 2

Henrique Forlani
Henrique Forlani

Reputation: 1353

Create classes as @x... pointed in the comment in order to build your tree

public class features
{
   public string type {get;set;}
   public int maxResults {get;set;}
}
public class requests 
{
   public List<features> {get;set;}
   ... the same for images
}

Populate it, serialize it and send the request...

Upvotes: 0

Related Questions