nikk
nikk

Reputation: 2877

JSON array to C# List

How can I deserialize this simple JSON string to a list in C# ?

["on4ThnU7","n71YZYVKD","CVfSpM2W","10kQotV"]

such that,

List<string> myStrings = [the content of the JSON above]

I am using DataContractJsonSerializer found in System.Runtime.Serialization.Json, and don't need external library.

EDIT: JavaScriptSerializer found in System.Web.Script.Serialization is also acceptable.

Upvotes: 0

Views: 1786

Answers (6)

Mushroomator
Mushroomator

Reputation: 9258

Modern C#: System.Text.Json

Since .NET Core 3.1 .NET comes with the System.Text.Json namespace which allows JSON (De-)Serialization without using any library.

From the Microsoft documentation:

The System.Text.Json namespace provides functionality for serializing to and deserializing from JavaScript Object Notation (JSON). The System.Text.Json library is included in the runtime for .NET Core 3.1 and later versions. For other target frameworks, install the System.Text.Json NuGet package. The package supports:

  • .NET Standard 2.0 and later versions
  • .NET Framework 4.7.2 and later versions
  • .NET Core 2.0, 2.1, and 2.2

To deserialize you need to use an appropriate type of your choice that can hold multiple values like e.g IEnumerable<string>, List<string>, IReadOnlyCollection<string> etc. whatever is the datatype that fits your needs best.

Using C# 11 and .NET 7 you can now use raw string literals, which makes declaring JSON in code much easier and more readable and you don't need to escape every ".

using System.Text.Json;

var content = """
    [
      "on4ThnU7", 
      "n71YZYVKD", 
      "CVfSpM2W", 
      "10kQotV"
    ]
    """;
var serialized = JsonSerializer.Deserialize<IReadOnlyCollection<string>>(content);
foreach (var item in serialized)
{
    Console.WriteLine(item);
}

Expected output:

on4ThnU7
n71YZYVKD
CVfSpM2W
10kQotV

For how to migrate from Newtonsoft.Json to System.Text.Json see the Microsoft documentation.

Upvotes: 0

Asif Rehman
Asif Rehman

Reputation: 3

JavaScriptSerializer serializer = new JavaScriptSerializer(); List stringList = serializer.Deserialize>(inpustJson);

Upvotes: 0

ekad
ekad

Reputation: 14624

You can use Json.Net, make sure you import Newtonsoft.Json namespace

using Newtonsoft.Json;

and deserialize the json as below

string json = @"[""on4ThnU7"",""n71YZYVKD"",""CVfSpM2W"",""10kQotV""]";
List<string> myStrings = JsonConvert.DeserializeObject<List<string>>(json);
foreach (string str in myStrings)
{
    Console.WriteLine(str);
}

Output

on4ThnU7
n71YZYVKD
CVfSpM2W
10kQotV

Working demo: https://dotnetfiddle.net/4OLS2v

Upvotes: 1

nikk
nikk

Reputation: 2877

Ok, I got it.

using System.Web.Script.Serialization;

public List<string> MyJsonDeserializer(string filename)
{
    //get json data
    Stream fs = new FileStream(filename, FileMode.Open);
    string jsonData = new StreamReader(fs).ReadToEnd();
    fs.Close(); 

    //deserialize json data to c# list
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    return (List<string>)serializer.Deserialize(jsonData, typeof(List<string>));        
}     

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222722

Just do this,

  string json = "[\"on4ThnU7\",\"n71YZYVKD\",\"CVfSpM2W\",\"10kQotV\"]";
  var result = new JavaScriptSerializer().Deserialize<List<String>>(json);

Upvotes: 3

AndreyAkinshin
AndreyAkinshin

Reputation: 19061

You can convert the string data to bytes[], wrap it in a MemoryStream, and use DataContractJsonSerializer for deserialization:

string stringData = "[\"on4ThnU7\", \"n71YZYVKD\", \"CVfSpM2W\", \"10kQotV\"]";
string[] arrayData;
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(stringData)))
{
    var deserializer = new DataContractJsonSerializer(typeof(string[]));
    arrayData = deserializer.ReadObject(ms) as string[];
}
if (arrayData == null) 
    Console.WriteLine("Wrong data");
else
{
    foreach (var item in arrayData) 
        Console.WriteLine(item);
}

Upvotes: 1

Related Questions