-1

After hours of searching and trying, can someone please be so kind and help me solving this following simple problem:

I have the following JSON-String:

[
    {
        "key": 1234,
    },
    {
        "key": 9876,
    }
]

How can I read this JSON and write all values into a List?

Had many attempts so far, but please see following code:

List<int> content = new List<int>;
var json = reader.ReadToEnd();

var obj = JObject.Parse(json);                    

First try:

foreach(var key in obj)
{
    content.Add((int)obj["key"]);
}

Other try:

var token = obj.SelectToken("key");

foreach(var item in token)
{
   content.Add(JsonConvert.DeserializeObject<int>(item.value));
}

Or something this way?

foreach(var key in obj)
{
    content.Add(Int32.Parse(obj.GetValue("key").ToString()));
}

Trying to run the last attempt, I get following error message: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Even if the JSON looks like the following:

[{\"key\":9999},{\"key\":9876}]

Would be very happy for every answer.

Best regards

Sam
  • 145
  • 1
  • 1
  • 12
  • Possible duplicate of [Deserialize list of objects in C#](https://stackoverflow.com/questions/43415938/deserialize-list-of-objects-in-c-sharp) – Thierry Prost May 03 '19 at 14:24

3 Answers3

1

Use Newtonsoft.Json

It can be done in the following way:

    List<string> yourList = JsonConvert.DeserializeObject(YourJson).ToList();

NOTE: It can only be saved as a list of strings , but can be called with: yourList.YourKeyName.

  • I added the following: return JsonConvert.DeserializeObject(json).ToList(); Unfortunately he says: "object" does not contain a Definition for "ToList" (Maybe a using-directive is missing)" – Sam May 03 '19 at 14:37
  • Make sure your function is a `List` aswell. – arlan schouwstra May 03 '19 at 14:45
  • I rechecked it again. Yes, my function is List as well: private List getKey(string ip){List content = new List();var request = HttpWebRequest.Create(string.Format(ip,path)); using (HttpWebResponse response = request.GetResponse() as HttpWebResponse){using StreamReader reader = new StreamReader(response.GetResponseStream())){var json = reader.ReadToEnd();content = JsonConvert.DeserializeObject(json).ToList();}}return content;} – Sam May 06 '19 at 12:20
0

Depends on what you want but you could also create a specified class for your json. The following class represents your json string.

public class RootObject
{
    public int key { get; set; }
}

You could then deserialise your json string as follows:

string json=reader.ReadToEnd();

List<RootObject> myobs=JsonConvert.DeserialiseObject<List<RootObject>>(json);

You can then do stuffs with the list.

foreach(var ob in myobs){
Console.WriteLine(ob.key);
}
bolkay
  • 1,881
  • 9
  • 20
0

Following on to what @bolkay said, you need to define your object:

public class KeyClass
{
    public int Key { get; set; }
}

and then if your JSON is in a variable called jsString for example

        List<int> content = new List<int>();
        var keys = JsonConvert.DeserializeObject<List<KeyClass>>(jsString);
        foreach (var item in keys)
        {
            content.Add(item.Key);
        }