1

I've looked and can't find anything and this is really starting to annoy me...

I've got JSON.Net and the following snippet of code

var x = insList.Select(a => new
{
    ac = a.CreatedDate,
    bd = a.CreatedBy
 });
 this.Context.Response.Write(x.ToJSON());

.ToJSON() is a simple extension method:

public static string ToJSON(this object obj)
    { return JsonConvert.SerializeObject(obj); }

The json output is

enter image description here

Ideally what I'd like is the highlight bits to have the same root name, rather than just {}

Can anyone help please?

1 Answer 1

2

Objects do not have names in JSON, properties do. (See JSON.org.) Therefore, if you want to name an object, you'll have to make it the value of a property of another containing object.

var x = insList.Select(a => new
{
    rootName = new 
    {
        ac = a.CreatedDate,
        bd = a.CreatedBy
    }
});

This will yield the following JSON:

[
  {
    "rootName": {
      "ac": "0001-01-01T00:00:00",
      "bd": 0
    }
  },
  {
    "rootName": {
      "ac": "0001-01-01T00:00:00",
      "bd": 0
    }
  },
  {
    "rootName": {
      "ac": "0001-01-01T00:00:00",
      "bd": 0
    }
  }
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.