0

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())
});
8
  • That is already json, you can't serialize it any further. Just use the json as the StringContent. Commented Jul 28, 2016 at 23:32
  • @Crowcoder Can i create a class that represents this tree ? if so what should it look like ?, i don't wanna serialize this string i wanna create one on demand that looks like this Commented Jul 28, 2016 at 23:33
  • 1
    Create a class, which has a structure like that. Fill it. Serialize it as string. Then send it through HttpClient. Commented Jul 28, 2016 at 23:37
  • If you create a class you can let an extension of HttpClient handle the serialization for you: msdn.microsoft.com/en-us/library/…' Commented Jul 28, 2016 at 23:44
  • @Crowcoder What the class should look like to be serialized into this format ?, can you provide an answer with a class ? Commented Jul 28, 2016 at 23:47

2 Answers 2

2

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/

Sign up to request clarification or add additional context in comments.

1 Comment

I always try to take the lazy road ;)
0

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...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.