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
  • check out stackoverflow.com/questions/13506542/… Commented Dec 2, 2014 at 4:57
  • I saw that already. The JSON data structure is really different. Commented Dec 2, 2014 at 5:02

6 Answers 6

3

Just do this,

  string json = "[\"on4ThnU7\",\"n71YZYVKD\",\"CVfSpM2W\",\"10kQotV\"]";
  var result = new JavaScriptSerializer().Deserialize<List<String>>(json);
Sign up to request clarification or add additional context in comments.

3 Comments

why does it has "\" though? unlike post above
Thats how you format json, otherwise compiler woll show an error!
got it! given that the json is provided plainly within the code. lesson learned on that.
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);
}

Comments

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 Comments

thanks ekad! Much like my answer above. I appreciate it lots. Hope you can be there again next time! :)
where is JsonConvert though? didn't see it under that namespace.
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.
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.
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 Comment

what is the difference to the answer i have posted above?
0

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.