13

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": "email1@email.com",
      "status": "good2go"
    },
    {
      "email_address": "email2@email.com",
      "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.

Blankdud
  • 698
  • 3
  • 9
  • 22
  • what are you actually getting? – Arpit Feb 26 '16 at 14:34
  • Why are your annoying yourself with anonymous objects ? Use datacontrat instead or name attribute http://www.newtonsoft.com/json/help/html/JsonPropertyName.htm – cdie Feb 26 '16 at 14:34
  • @ Arpit The closest I have gotten is the same output without the operations string before the array. – Blankdud Feb 26 '16 at 14:48

4 Answers4

14

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

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

        List<MyClass> data = new List<MyClass>() { new MyClass() { email_address = "email1@email.com", status = "good2go" }, new MyClass() { email_address = "email2@email.com", status = "good2go" } };
        var json = JsonConvert.SerializeObject(new
        {
            operations = data
        });
James Dev
  • 2,929
  • 1
  • 10
  • 16
3
class MyClass
{
     public string email_address { get; set; }
     public string status { get; set; }
}

List<MyClass> data = new List<MyClass>() { new MyClass() { email_address = "email1@email.com", status = "good2go" }, new MyClass() { email_address = "email2@email.com", status = "good2go" } };

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

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

You can try with something like this:

using System.Web.Script.Serialization;
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(data);
Claudio
  • 642
  • 3
  • 12
-1

Here is the simple code

JArray.FromObject(objList);

  • To be able to understand your answer more details are needed. Currently it looks to me that this will not work. – surfmuggle May 05 '22 at 10:50