0

How do I return an array of json objects with dynamic keys, for example:

[
    "dynamic prop 1": {
          "title": "abc",
          "sku": "123"
        },
    "dynamic prop 2": {
          "title": "xyz",
          "sku": "789"
        }
]

The default formatting is:

[
        {
          "title": "abc",
          "sku": "123"
        },
        {
          "title": "xyz",
          "sku": "789"
        }
]
7
  • I'm assuming you are using the .NET dynamic type? Commented Jul 13, 2016 at 13:58
  • No. I just wanted to emphasize that the the property could be anything. For example, the title and sku are properties I know but the "key/name/id" of the object could be any string. Commented Jul 13, 2016 at 14:25
  • 1
    Understood, but you are constructing this object on the server. So you can use the dynamic type and return a JObject. Commented Jul 13, 2016 at 14:37
  • Yes, on the server. Currently I'm returning this: return data.Select(x => new { title = x.title, sku = x.sku }); Commented Jul 13, 2016 at 15:05
  • use a stringbuilder and simply build the json string which you want. Commented Jul 13, 2016 at 15:31

4 Answers 4

1

Using JObject solved the problem:

JObject jProducts= new JObject();

foreach (var p in products)
{
    var o = new JObject()
    {
        { "title",  p.Title},
        { "sku", p.Sku }
    };

    jProducts.Add(p.Name, o);
}

return Request.CreateResponse(HttpStatusCode.OK, jProducts);

Thanks to william-xifaras

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

Comments

0

Use return List of objects. Where object (say MyObj)having properties: title and sku. then yuo will get desired output. Your data to be returned will look like:

List<MyObj> data=new List<MyObj>();
// add your objects.
// return this list object.

u will get you output in format you want.

1 Comment

That's incorrect. It's the default formatting which I am getting already.
0

then return dynamic object.

return new{ property1Name=MyObj1,property2Name=MyObj2}

I hope this will work for you.

Otherwise refer following link to generate c# classes from json and create required model in ur solution. https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjEl7efl_XNAhWJs48KHYDHAUsQFggfMAA&url=http%3A%2F%2Fjson2csharp.com%2F&usg=AFQjCNEbR-mTF-PU4BYWff3opCDcJOl0ag&bvm=bv.127178174,d.c2I

1 Comment

That's what I'm currently doing but it does not solve the problem. The "property1Name" is a variable so I can't use the above syntax.
0

Then You refer

Tuple data type and learn about it.

It may wotk for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.