0
#table1#
pid  property   address
1    property1  Ashfield
2    property2  Burwood

#table2#
id  images pid
1   img1   1
2   img2   1
3   img3   2

How can I generate json data like below from above table using c# using asp.net?

property[
   {
   id: 1,
   property: property1,
   address: Ashfield,
   images:[
       images: img1,
       images: img2
   ]},
   id: 2,
   property: property2,
   address: Burwood,
   images:[
       images: img3
   ]}
]

3 Answers 3

1

Simply construct the nested object as a class, and then serialize to JSON.

As long as you can represent the JSON object as a class structure, then you can convert easilly to/from it.

[Table(name="address")]
public class Address{
  [Datamember(Name="images")]
  public IEnumerable<Image> Images{get;set;}
}
Sign up to request clarification or add additional context in comments.

Comments

0
using (var ctx = new DatabaseEntities())
            {
                var prop = from p in ctx.properties.Include("images")
                           select new
                           {
                               id = p.pid,
                               address = p.address,
                               property = p.property1,
                               images = (from img in p.images select new { images = img.images})
                           };

                var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                string jsonString = javaScriptSerializer.Serialize(prop.ToList());

                Console.WriteLine(jsonString);
            }

Json returned from the above code is:

[
   {
      "id": 1,
      "address": "Ashfield",
      "property": "property1",
      "images": [
         {
            "images": "img1"
         },
         {
            "images": "img2"
         }
      ]
   },
   {
      "id": 2,
      "address": "Burwood",
      "property": "property2",
      "images": [
         {
            "images": "img3"
         }
      ]
   }
]

Comments

0

Thanks for answer. I have this code

DataTable dataTable = blproperty.PropertyAll();

        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();  
        List > parentRow = new List > ();  
        Dictionary  childRow;  
        foreach(DataRow row in dataTable.Rows) 
        {  
            childRow = new Dictionary  ();  
            foreach(DataColumn col in dataTable.Columns) 
            {  
                childRow.Add(col.ColumnName, row[col]);  
            }  
            parentRow.Add(childRow);  
        }  
        context.Response.Write(jsSerializer.Serialize(parentRow));

Is there easy way to do modifying this?

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.