0

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.

2

6 Answers 6

3

Just do this,

  string json = "[\"on4ThnU7\",\"n71YZYVKD\",\"CVfSpM2W\",\"10kQotV\"]";
  var result = new JavaScriptSerializer().Deserialize<List<String>>(json);
3
  • why does it has "\" though? unlike post above
    – nikk
    Commented Dec 2, 2014 at 5:43
  • 1
    Thats how you format json, otherwise compiler woll show an error! Commented Dec 2, 2014 at 5:44
  • got it! given that the json is provided plainly within the code. lesson learned on that.
    – nikk
    Commented Dec 2, 2014 at 5:49
1

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);
}
1

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

4
  • thanks ekad! Much like my answer above. I appreciate it lots. Hope you can be there again next time! :)
    – nikk
    Commented Dec 2, 2014 at 5:24
  • where is JsonConvert though? didn't see it under that namespace.
    – nikk
    Commented Dec 2, 2014 at 5:26
  • so that's what I was saying: I didn't want to use any of those external libs. don't want to deal with dependencies when application is deployed. it MUST be a System.something namespace.
    – nikk
    Commented Dec 2, 2014 at 5:36
  • If that's the case, then Sajeetharan's answer is what you're looking for. I'm just giving an alternative of using json.net.
    – ekad
    Commented Dec 2, 2014 at 5:38
0

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>));        
}     
1
  • 2
    what is the difference to the answer i have posted above? Commented Dec 2, 2014 at 5:25
0

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

0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.