Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 694
Blankdud Avatar asked Feb 26 '16 14:02

Blankdud


People also ask

Can you convert list to JSON?

To convert a list to json in Python, use the json. dumps() method. The json. dumps() is a built-in function that takes a list as an argument and returns the json value.

Can JSON be a list of objects?

A resource representation, in the JSON format, is a complex JSON object. Lists of items and nested data structures are represented as JSON arrays and nested JSON objects. A resource that returns a list of items, represents those items in the following standard format: {"data": [{…},{…}]}

Can JSON have an array of objects?

JSON array can store multiple values. It can store string, number, boolean or object in JSON array. In JSON array, values must be separated by comma.

What is a JSONArray?

JsonArray represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array. A JsonArray object can be created by reading JSON data from an input source or it can be built from scratch using an array builder object.


1 Answers

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);
like image 72
Theo Fernandes Avatar answered Oct 02 '22 22:10

Theo Fernandes