Reputation: 2659
Suppose I have this json saved in my database ?
{
"Type": "IPS",
"Size": "4.7 Inch",
"Protection": "OGS with full lamination technology"
}
The number of the properties are dynamic. Which means for another row my be 5 or 6 properties. Is there any way to loop over it and retrieve them as objects.
So I want to get the type, size, Protection as fileds to create another json format. How can I do this ?
JObject is a good solution. But let us say I am looping thorough rows to create a dynamic object, only for the json field I want to loop over it and add the properties to the dynamic object that i am creating. Can I achieve this ?
For Example:
I ave this
var dataTable= DbHelper.GetDatatable(StoredProcedureName);
now
foreach (DataRow row in rows)
{
var attributes = row["Attributes"].ToString();
var obj = new
{
Id = (int)row["ID"],
Name = row["ProductName"].ToString()
};
list.Add(obj);
}
so row attributes contain the json specified earlier,
Can I loop now to get this final result
var obj = new
{
Id = (int)row["ID"],
Name = row["ProductName"].ToString(),
Type = IPS,
Size = 4.7 Inch,
Protection = OGS with full lamination technology
};
Upvotes: 2
Views: 179
Reputation: 1808
Are you using Json.NET? If not, I'd highly recommend it. If you add it to your project, it becomes as simple as this:
JObject json = JObject.Parse(str);
Here is more information on Json.NET: http://www.newtonsoft.com/json/help/html/Introduction.htm
Upvotes: 4
Reputation: 354
You best use an existing JSON library for that. Newtonsoft JSON comes to mind.
Example (stolen from their home page)
string json = @"{
'Name': 'Bad Boys',
'ReleaseDate': '1995-4-7T00:00:00',
'Genres': [
'Action',
'Comedy'
]
}";
Movie m = JsonConvert.DeserializeObject<Movie>(json);
string name = m.Name;
// Bad Boys
Upvotes: 2
Reputation: 21657
You could create a tabelar function that has as parameter this string and inside you split your string in columns and return the result as a table row and make an outer apply with the strings table
Upvotes: 0