Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

.net

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

like image 286
David Thielen Avatar asked Aug 26 '13 20:08

David Thielen


1 Answers

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"}]}

like image 143
I4V Avatar answered Nov 15 '22 04:11

I4V