Blankdud
Blankdud

Reputation: 698

Converting list of objects to json array

I have a List of class objects that have email address and status data members. I am trying to convert these to a json, making sure to have the "operations" word on the array.

This is my class:

class MyClass
{
    public string email {get; set; }
    public string status { get; set; }
}

This is my current code (not building):

List<MyClass> data = new List<MyClass>();
data = MagicallyGetData();

string json = new {
     operations = new {
          JsonConvert.SerializeObject(data.Select(s => new {
               email_address = s.email,
               status = s.status
          }))
     }
};

This is the JSON I am trying to get:

{
  "operations": [
    {
      "email_address": "[email protected]",
      "status": "good2go"
    },
    {
      "email_address": "[email protected]",
      "status": "good2go"
    },...
  ]
}

EDIT1 I should mention that the data I am getting for this comes from a DB. I am de-serializing a JSON from the DB and using the data in several different ways, so I cannot change the member names of my class.

Upvotes: 13

Views: 66160

Answers (4)

James Dev
James Dev

Reputation: 3009

I believe this will give you what you want. You will have to change your class property names if possible.

Given this class

class MyClass
{
   public string email_address { get; set; }
   public string status { get; set; }
}

You can add the objects to a list

List<MyClass> data = new List<MyClass>()
{ 
   new MyClass(){email_address = "[email protected]", status = "s1"}
   , new MyClass(){ email_address = "[email protected]", status = "s1"}
};

Using an anonymous-type you can assign data to the property operations

var json = JsonConvert.SerializeObject(new
{
   operations = data
});

Upvotes: 13

Syed Nazir Hussain
Syed Nazir Hussain

Reputation: 441

Here is the simple code

JArray.FromObject(objList);

Upvotes: -1

Theo Fernandes
Theo Fernandes

Reputation: 81

class MyClass
{
     public string email_address { get; set; }
     public string status { get; set; }
}

List<MyClass> data = new List<MyClass>() { new MyClass() { email_address = "[email protected]", status = "good2go" }, new MyClass() { email_address = "[email protected]", status = "good2go" } };

//Serialize
var json = JsonConvert.SerializeObject(data);

//Deserialize
var jsonToList = JsonConvert.DeserializeObject<List<MyClass>>(json);

Upvotes: 4

Claudio
Claudio

Reputation: 652

You can try with something like this:

using System.Web.Script.Serialization;
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(data);

Upvotes: 0

Related Questions