2

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

};
2
  • 2
    You can do this if you are using Json.Net JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json). Commented Feb 17, 2016 at 6:53
  • @HariPrasad Thanks so much it helped. Commented Mar 1, 2016 at 10:52

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

I modified my question, any help on it.
2

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.