Serializing a list to JSON
If using .Net Core 3.0 or later;
Default to using the built in System.Text.Json
parser implementation.
e.g.
using System.Text.Json;
var json = JsonSerializer.Serialize(aList);
alternatively, other, less mainstream options are available like Utf8Json parser and Jil: These may offer superior performance, if you really need it but, you will need to install their respective packages.
If stuck using .Net Core 2.2 or earlier;
Default to using Newtonsoft JSON.Net as your first choice JSON Parser.
e.g.
using Newtonsoft.Json;
var json = JsonConvert.SerializeObject(aList);
you may need to install the package first.
PM> Install-Package Newtonsoft.Json
For more details see and upvote the answer that is the source of this information.
For reference only, this was the original answer, many years ago;
// you need to reference System.Web.Extensions
using System.Web.Script.Serialization;
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(aList);
how to serialize nested list into json format
Say you have two list
public class Customer
{
[JsonProperty("customer_id")]
public int CustomerId { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("products")]
public List<Products> Products { get; set; }
}
public class Products
{
[JsonProperty("product_id")]
public string ProductId { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
//initialize Object of Customer here
Use Newtonsoft to convert Customer object into json
var jsonString = JsonConvert.SerializeObject(objCustomer);
You can also take advantage of several formatting options available.
Update
Per your comment - pass the serialize data
return Ok(JsonConvert.SerializeObject(objCustomer))
Also, if you direct pass objCustomer like
return Ok(objCustomer)
it should return you Json (provided you have not configured your project to return another format by default)
Serializing a list of Object using Json.NET
You should try this:
https://surajdeshpande.com/2013/10/01/json-net-examples/
string jsonString = JsonConvert.SerializeObject(userList);
Deserialize JSON to an Object:
JsonConvert.DeserializeObject<User>(jsonString);
Serializing list to JSON
You can use pure Python to do it:
import json
list = [1, 2, (3, 4)] # Note that the 3rd element is a tuple (3, 4)
json.dumps(list) # '[1, 2, [3, 4]]'
Serialize Json file with separate list and object
Check your json format or compare with below format
var json = @"{
'UsbDevices': [
'SA',
'SB',
'SC',
'SE2',
'SF',
'M'],
'DeviceConnectivityExperationDateTime' : '2020-12-30'
}";
var items = JsonConvert.DeserializeObject<Data>(json);
}
public class Data
{
public Data()
{
this.UsbDevices = new List<string>();
}
public List<string> UsbDevices { get; set; }
public string DeviceConnectivityExperationDateTime { get; set; }
}
Serializing a List of Objects in Java to json
Found a SerializationFeature WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED
by which we can obtain the above mentioned scenario in JSON
json serialization of a list of objects of a custom class
I've solved this by adding an encode method to the class:
def encode(self):
return self.__dict__
and adding some arguments to json.dumps:
jsontracks = json.dumps(tracklist, default=lambda o: o.encode(), indent=4)
This will "crawl" down your class tree (if you have any child classes) and encode every object as a json list/object automatically. This should work with just about any class and is fast to type. You may also want to control which class parameters get encoded with something like:
def encode(self):
return {'name': self.name,
'code': self.code,
'amount': self.amount,
'minimum': self.minimum,
'maximum': self.maximum}
or a little bit faster to edit (if you're lazy like me):
def encode(self):
encoded_items = ['name', 'code', 'batch_size', 'cost',
'unit', 'ingredients', 'nutrients']
return {k: v for k, v in self.__dict__.items() if k in encoded_items}
full code:
import json
class Song:
def __init__(self, sname, sartist, coverart, albname, albartist, spotid):
self.sname = sname
self.sartist = sartist
self.coverart = coverart
self.albname = albname
self.albartist = albartist
self.spotid = spotid
def encode(self):
return self.__dict__
tracklist = [
Song('Imagine', 'John Lennon', None, None, None, None),
Song('Hey Jude', 'The Beatles', None, None, None, None),
Song('(I Can\'t Get No) Satisfaction', 'The Rolling Stones', None, None, None, None),
]
jsontracks = json.dumps(tracklist, default=lambda o: o.encode(), indent=4)
print(jsontracks)
output:
[
{
"sname": "Imagine",
"sartist": "John Lennon",
"coverart": null,
"albname": null,
"albartist": null,
"spotid": null
},
{
"sname": "Hey Jude",
"sartist": "The Beatles",
"coverart": null,
"albname": null,
"albartist": null,
"spotid": null
},
{
"sname": "(I Can't Get No) Satisfaction",
"sartist": "The Rolling Stones",
"coverart": null,
"albname": null,
"albartist": null,
"spotid": null
}
]
Related Topics
How to Know If a Process Is Running
Inner Join of Datatables in C#
Free File Locked by New Bitmap(Filepath)
Difference Between Console.Read() and Console.Readline()
How to Write a Backslash (\) in a String
Cross-Thread Operation Not Valid
How to Clean SQLdependency from SQL Server Memory
Deserializing JSON into an Object
What Does a Lock Statement Do Under the Hood
Parallel.Foreach VS Task.Factory.Startnew
Automatically Create an Enum Based on Values in a Database Lookup Table
Creating a Generic<T> Type Instance with a Variable Containing the Type
Detect If Running as Administrator with or Without Elevated Privileges
How to Use Visual Studio Code to Develop Unity3D Projects in Ubuntu