David Thielen
David Thielen

Reputation: 33046

How do I create JSON objects in C# where the property names are set on the fly?

I need to return an array of JSON objects that is the result of an SQL query. The SQL query can be anything so I need to create the property names as well as the values on the fly in code.

For example, "select first_name, last_name from employees" I want to return:

{ "data": 
   [{
        "first_name": "dave",
        "last_name": "thielen"
    },
    {
        "first_name": "john",
        "last_name": "smith"
    }]
}

But the next query could be "select item, price, tax, ship_date from orders and want to return:

{ "data": 
   [{
        "item": "HD TV",
        "price": "598.95"
        "tax": "59.89"
        "ship_date": "2013-08-26"
    },
    {
        "item": "Cables",
        "price": "54.67"
        "tax": "5.47"
        "ship_date": "2013-08-26"
    }]
}

How can I build this up in C# and then convert to JSON?

thanks - dave

Upvotes: 5

Views: 5830

Answers (2)

I4V
I4V

Reputation: 35373

Use anonymous types, For ex (using Json.Net),

var json = JsonConvert.SerializeObject(
    new { 
        data = new[]{ 
            new{name="a",surname="b"},
            new{name="c",surname="d"},
        } 
    }
    );

would give

{"data":[{"name":"a","surname":"b"},{"name":"c","surname":"d"}]}

EDIT

I need "a": "b"

var json = JsonConvert.SerializeObject(
        new Dictionary<string, string>() {
            { "a","b" }
        }
    );

output: {"a":"b"}

EDIT2

And a funny one

var dict = new Dictionary<string, string>() {
    { "a","b" },
    { "c","d" }
};

var json = JsonConvert.SerializeObject(
        new { data = dict.Select(x => new[]{x}.ToDictionary(kv => kv.Key, kv => kv.Value)) }
    );

Output: {"data":[{"a":"b"},{"c":"d"}]}

Upvotes: 8

Justin Drury
Justin Drury

Reputation: 748

My suggestion would be to look at Json.NET

There are a couple other libraries out there but I think that is the most used. It has a simple serialize/deserialize API.

Upvotes: 0

Related Questions