Newbie
Newbie

Reputation: 361

Convert dictionary to custom json object c#

Here is something i couldn't get around my head even after spending a few hours. Hoping someone will direct me.

I have a Dictionary object which I want to convert to JSON.

Sample code:

Dictionary<String,String> users = new Dictionary<String,String>();

Users look something like this:

{[name1, department1],[name2, department2]}

Here is the custom JSON format for each user:

public class User
{
    public string name;
    public string dept;
    // has get and set methods for each.
}

How can I write the users Dictionary as a JSON object of type user?

Upvotes: 0

Views: 149

Answers (1)

David
David

Reputation: 219016

Ideally if the dictionary represents a collection of user objects then it in fact should be a collection of user objects. But failing that, it can easily be transformed into one:

users.Select(u => new user { name = u.Key, dept = u.Value });

The resulting enumerable can then be serialized using pretty much any serializer.

Upvotes: 3

Related Questions