I've done something like before using the JavaScript serialization class:

using System.Web.Script.Serialization;

And:

JavaScriptSerializer jss = new JavaScriptSerializer();

string output = jss.Serialize(ListOfMyObject);
Response.Write(output);
Response.Flush();
Response.End();
Answer from Mark Ursino on Stack Overflow
🌐
Wtools
wtools.io › convert-list-to-json-array
Convert List to JSON Array Online - wtools.io
Just paste your list to the textarea above and click to the button "Convert" and you will get JSON array in the next textarea.
🌐
Java Guides
javaguides.net › 2019 › 07 › convert-list-to-json-array-using-jackson.html
Convert List to JSON Array Using Jackson
July 21, 2019 - ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); List < String > progLangs = new ArrayList < > (); progLangs.add("C"); progLangs.add("C++"); progLangs.add("Java"); progLangs.add("Java EE"); progLangs.add("Python"); progLangs.add("Scala"); progLangs.add("JavaScript"); // Serialize Object to JSON. String json = mapper.writeValueAsString(progLangs); // Print json System.out.println(json); } } [ "C", "C++", "Java", "Java EE", "Python", "Scala", "JavaScript" ] Jackson - Convert Java Object to/from JSON Example (popular)
Discussions

android - convert ArrayList<MyCustomClass> to JSONArray - Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... I have an ArrayList that I use within an ArrayAdapter for a ListView. I need to take the items in the list and convert them to a JSONArray ... More on stackoverflow.com
🌐 stackoverflow.com
Convert string List data to json format
Hello Everyone I need your help. I'm working on windows service on 4.0 version using c# i want to convert string list to json format and pass that json data to third party. My code is:- List msisd... More on c-sharpcorner.com
🌐 c-sharpcorner.com
6
August 17, 2017
c# - Serializing a list to JSON - Stack Overflow
I did not want to have to always check if the type of a parameter is a string and convert it to an array. I'm using Json.NET (which is now built into C#), and I convert my List to an array and let the converter handle the rest. More on stackoverflow.com
🌐 stackoverflow.com
Newest Questions - Stack Overflow
Stack Overflow | The World’s Largest Online Community for Developers More on stackoverflow.com
🌐 stackoverflow.com
🌐
Cubot
blog.cubot.net › latest › guide › convert-list-of-object-to-json-string-c_58016.html
Convert C Object Lists To Json Strings: A Step-By-Step Guide
November 18, 2024 - This comprehensive guide walks you through the process of converting C object lists into JSON strings, offering clear step-by-step instructions, practical examples, and advanced techniques. Discover helpful tips, common pitfalls to avoid, and effective troubleshooting strategies to enhance your coding skills and streamline your development workflow.
🌐
Aspdotnet-suresh
aspdotnet-suresh.com › 2017 › 02 › convert-list-object-to-json-string-in-csharp-vbnet.html
Convert List Object to JSON String in C#, VB.NET
how to convert list object to JSON string in asp.net using c#, vb.net with example or how to convert JSON string to generic list in c#, vb.net with example or convert list of objects to JSON string in asp.net using c#, vb.net with example. By using newtonsoft.json reference in our asp.net applications we can easily convert list object to JSON string or JSON string to list object based on our requirements.
Find elsewhere
Top answer
1 of 9
456

If using .Net 6.0 or later;

Default to using the built in System.Text.Json parser implementation with Source Generation. Its a little more typing and compiling but, is more efficient at runtime.

The "easier to code" option below, still works but, less efficiently because it uses Reflection at runtime. The new method has some intentional, by design limitations. If you can't change your model to avoid those, the Reflection based method remains available.

e.g.

using System.Text.Json;
using System.Text.Json.Serialization;

var aList = new List<MyObjectInJson>
{
    new(1, "1"),
    new(2, "2")
};

var json = JsonSerializer.Serialize(aList, Context.Default.ListMyObjectInJson);
Console.WriteLine(json);

return;

public record MyObjectInJson
(
    long ObjectId,
    string ObjectInJson
);

[JsonSerializable(typeof(List<MyObjectInJson>))]
internal partial class Context : JsonSerializerContext
{
}

If using .Net Core 3.0 to .Net 5.0, it is time to upgrade;

Default to using the built in System.Text.Json parser implementation.

e.g.

using System.Text.Json;

var json = JsonSerializer.Serialize(aList);

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);
2 of 9
124

You can also use Json.NET. Just download it at http://james.newtonking.com/pages/json-net.aspx, extract the compressed file and add it as a reference.

Then just serialize the list (or whatever object you want) with the following:

using Newtonsoft.Json;

string json = JsonConvert.SerializeObject(listTop10);

Update: you can also add it to your project via the NuGet Package Manager (Tools --> NuGet Package Manager --> Package Manager Console):

PM> Install-Package Newtonsoft.Json

Documentation: Serializing Collections

🌐
Thiago Passos
passos.com.au › converting-json-object-into-c-list
Converting JSON Objects into C# List<> - Thiago Passos
March 7, 2019 - The DataRequest would look something along these lines, but the Players property wouldn't be bound as it expects a JSON array instead of an object. public class DataRequest { public bool Status {get;set;} public string Version {get;set;} [JsonProperty("status_code")] public int StatusCode {get;set;} public TimeSpan Expires {get;set;} public List<Player> Player {get;set;} } There it comes a custom JsonConverter from Newtonsoft for the win. public class PlayersConverter : JsonConverter { // This is used when you're converting the C# List back to a JSON format public override void WriteJson(JsonW
🌐
Nextjson
nextjson.com › array
List to Array Converter Online - NextJSON
See how NextJSON can convert your lists to arrays with different quote styles. ... Enable both "Remove Duplicates" and "Ignore Case" to remove duplicates while ignoring letter case differences ... Paste a list of items—one per line—and the tool converts it to a JSON array.
🌐
Stack Overflow
stackoverflow.com › questions › 72704451 › convert-list-to-json-array
c# - Convert List to JSON Array - Stack Overflow
Use ' instead of " in your JSON text. ... @ˈvɔlə I'm sorry - I didn't mean for it to be anything but satirical. We (especially me) are all guilty of writing questionable code. I see people on this site get way too serious sometimes and it's nice to be able to have a quick laugh ... public class State { public List<string> Cities { get; set; } public State(List<string> cities) { Cities = cities; } }
Top answer
1 of 9
22

As others have already pointed out, the reason you are not getting the results you expect is because your JSON does not match the class structure that you are trying to deserialize into. You either need to change your JSON or change your classes. Since others have already shown how to change the JSON, I will take the opposite approach here.

To match the JSON you posted in your question, your classes should be defined like those below. Notice I've made the following changes:

  1. I added a Wrapper class corresponding to the outer object in your JSON.
  2. I changed the Values property of the ValueSet class from a List<Value> to a Dictionary<string, Value> since the values property in your JSON contains an object, not an array.
  3. I added some additional [JsonProperty] attributes to match the property names in your JSON objects.

Class definitions:

class Wrapper
{
    [JsonProperty("JsonValues")]
    public ValueSet ValueSet { get; set; }
}

class ValueSet
{
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("values")]
    public Dictionary<string, Value> Values { get; set; }
}

class Value
{
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("diaplayName")]
    public string DisplayName { get; set; }
}

You need to deserialize into the Wrapper class, not the ValueSet class. You can then get the ValueSet from the Wrapper.

var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;

Here is a working program to demonstrate:

class Program
{
    static void Main(string[] args)
    {
        string jsonString = @"
        {
            ""JsonValues"": {
                ""id"": ""MyID"",
                ""values"": {
                    ""value1"": {
                        ""id"": ""100"",
                        ""diaplayName"": ""MyValue1""
                    },
                    ""value2"": {
                        ""id"": ""200"",
                        ""diaplayName"": ""MyValue2""
                    }
                }
            }
        }";

        var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;

        Console.WriteLine("id: " + valueSet.Id);
        foreach (KeyValuePair<string, Value> kvp in valueSet.Values)
        {
            Console.WriteLine(kvp.Key + " id: " + kvp.Value.Id);
            Console.WriteLine(kvp.Key + " name: " + kvp.Value.DisplayName);
        }
    }
}

And here is the output:

id: MyID
value1 id: 100
value1 name: MyValue1
value2 id: 200
value2 name: MyValue2
2 of 9
11

http://json2csharp.com/

I found the above link incredibly helpful as it corrected my C# classes by generating them from the JSON that was actually returned.

Then I called :

JsonConvert.DeserializeObject<RootObject>(jsonString); 

and everything worked as expected.

🌐
CSharp Academy
csharp.academy › home › how to convert json array to list in c#
How to Convert JSON Array to List in C# - CSharp Academy
November 23, 2024 - Working with JSON data is a common task in modern applications, and often you’ll encounter JSON arrays that need to be converted into C# lists for easy manipulation. In this guide, we’ll demonstrate how to convert a JSON array into a List in C# using Newtonsoft.Json.
🌐
C# Corner
c-sharpcorner.com › UploadFile › vendettamit › parsing-list-of-json-elements-as-list-with-json-net
Parsing List of JSON Elements as List With JSON.Net
November 11, 2020 - And so you will get a complete list of correct items and corrupted data. We'll use a JArray class from the namespace Newtonsoft.Json.Linq to parse the data as a list of arrays of objects and then we'll convert one by one each item to a typed object and add it to the list.