3

How can I created arraylist as shown below using asp.net, c#. I can created such array using JsonTextWriter , but don't want to add any other dll as part of my solution.

  [{ "id": "slide-img-1", "client": "nature beauty", "desc": "nature beauty photography" },
  { "id": "slide-img-2", "client": "nature beauty", "desc": "add your description here" },
  { "id": "slide-img-3", "client": "nature beauty", "desc": "add your description here" },
  { "id": "slide-img-4", "client": "nature beauty", "desc": "add your description here" },
  { "id": "slide-img-5", "client": "nature beauty", "desc": "add your description here" },
  { "id": "slide-img-6", "client": "nature beauty", "desc": "add your description here" },
  { "id": "slide-img-7", "client": "nature beauty", "desc": "add your description here"}];

Thanks,

Ashish

Community
  • 1
  • 1
ashish.chotalia
  • 3,696
  • 27
  • 28

2 Answers2

4

You can use a JavaScriptSerializer:

Assuming the entity in your array is something like:

public class Entity 
{
  public string id { get; set; }
  public string client { get; set; }
  public string desc {get; set; }

  [ScriptIgnore]
  public string PropertyThatIsIgnored { get;set; }
}

Then it is useable like so:

Entity[] entities = ...;
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(entities);

Alternatively, if more complex serialization is required, you may consider using a DataContractJsonSerializer, since it allows more extensibility when serializing / deserializing.

Community
  • 1
  • 1
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
  • I have List where I have multiple variables. I want to have id,client and desc only. – ashish.chotalia Jan 26 '12 at 12:28
  • @ashish.chotalia I have updated my answer to show how a property can be ignored, however if you wish to change property names I'd advise using the `DataContractJsonSerializer`. – Rich O'Kelly Jan 26 '12 at 12:33
  • Yups, that works. Can you please left me know how can I auto generate id ? – ashish.chotalia Jan 26 '12 at 12:35
  • @ashish.chotalia please ask a separate SO question for that, a lot more information will be required - at what point you wish to generate the id, how it will be mapped back to your entity etc. – Rich O'Kelly Jan 26 '12 at 12:42
2

Use JavaScriptSerializer class that comes with .NET framework.

Have a look here.

var js = new JavaScriptSerializer();
string myJson = js.Serialize(new string[] {"A", "B", "C"});
Aliostad
  • 80,612
  • 21
  • 160
  • 208