sacredMonster
sacredMonster

Reputation: 1

How to serialize c# object array into json object without an array

I want to use JsonConvert.Serialize in order to serialize a c# array class object into a json non-array object.

public list<employee> employees;

Output:

"{\"employees\":
{\"name\":\"Alex\",\"number\":\"25860340\"},
{\"name\":\"Tom\",\"number\":\"94085345\"}
}" 

Upvotes: 0

Views: 1466

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129807

The format you have asked for in your question would not be valid JSON, because objects are not allowed to follow one another directly unless they are part of an array (see JSON.org). However, you could transform your employee list into a dictionary and serialize that instead, so long as you had a suitable key to use. One idea would be to use the employee number as a key, for example:

var employees = new List<Employee>
{
    new Employee { name = "Alex", number = "25860340" },
    new Employee { name = "Tom", number = "94085345" }
};

var obj = new
{
    employees = employees.ToDictionary(e => e.number)
};

string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
Console.WriteLine(json);

That would give you this output, which is close to what you wanted:

{
  "employees": {
    "25860340": {
      "name": "Alex",
      "number": "25860340"
    },
    "94085345": {
      "name": "Tom",
      "number": "94085345"
    }
  }
}

If the employee number isn't actually unique, you could instead use each employee's position in the list as a key like this:

int i = 0;
var obj = new
{
    employees = employees.ToDictionary(e => i++)
};

This would give you the following output instead:

{
  "employees": {
    "0": {
      "name": "Alex",
      "number": "25860340"
    },
    "1": {
      "name": "Tom",
      "number": "94085345"
    }
  }
}

Upvotes: 1

Related Questions