Nested values with POST using Flurl

741 Views Asked by At

So I'm a Ruby dev messing with C# and trying to figure out how to use Flurl with my endpoint.

Here's the JSON I can pass successfully with Ruby.

  {
    type: "workorder.generated",
    data: [{
        id: order.id,
        type: "orders"
      },{
        id: second_order.id,
        type: "orders"
      },{
        id: bad_order.id,
        type: "orders"
      }
    ]
  }

So using C# with Flurl I'm not 100% on how to structure that.

var response = await GetAPIPath()
    .AppendPathSegment("yardlink_webhook")
    .WithOAuthBearerToken(GetAPIToken())
    .PostJsonAsync(new
    {
        type = "workorder.generated",
        data = new
        {

        }

    })
    .ReceiveJson();

Any help on getting that data nested similar to the Ruby example?

2

There are 2 best solutions below

1
On BEST ANSWER

check this

var x = new
{
    type = "workorder.generated",
    data = new[]{ new {
        id= 1,
        type= "orders"
      },new {
        id= 2,
        type= "orders"
      },new {
        id= 3,
        type= "orders"
      }
    }
}
0
On

So flurl accepts couple of different inputs,

  • first is json string: You can serialize your object and pass into it,
  • second is object: Pass in the C# object into it - what you are currently doing.

Both requires you to have your data as an object. There are 2 ways to create your object.

  • Create your data structure in terms of classes,
  • Create an anonymous object - what @Derviş suggests

If you are frequently using this data model, and need to manipulate I'd suggest creating classes to model your object.

Here is how you can create classes for your needs:

public class YourObject {
    public string type;
    public List<YourDataObject> data;
}

public class YourDataObject {
    public string id;
    public string type;
}

You'll need to know how to initialize an object and set data to it, but this is the overall idea.