C# is not able to convert my Character to String in a Foreach loop

I am using a simple code to read the JSON data. I previously needed some help in that, but I am able to overcome the exception through a Google search about the error. But this time, there is no exception instead it is an un-understandable statement.

The statement is,

Unable to convert 'char' to 'string'.

I do understand that there was a trouble while casting the character data type to a string data type. But I never used any Character sequence in my code at all.

Here is the code I am using,

Stream fs = File.Open(new MainWindow().getFileName("events"), FileMode.Open);
if (fs.Length != 0)
{
    // File is not empty!
    JsonObject jsonObject = (JsonObject)JsonObject.Load(fs);
    // Get each event
    foreach (string events in jsonObject["allEvents"].ToString()) {
        /* here is the error */
    }
}

I am getting the array, from the JSON file. And converting it into a String, but it keeps telling me I can't. The file content is as

{  
    "allEvents":  [  
         {  
             "eventId": 1,  
             "eventType":  "birthday"  
         },  
         {  
             "eventId": 2,  
             "eventType": "meeting"  
         }  
    ]  
}

Right now, I really don't know what is wrong and how is wrong. But I can't get it to work. Please guide me!

Snapshot for the error: It is compile time error, not a runtime (After adding the code from Jon Skeet)

enter image description here

Jon Skeet
people
quotationmark

You're using foreach on a string. Effectively:

string x = "foo";
foreach (string y in x)

That makes no sense - a string is a sequence of characters, not a sequence of strings. In order to get the code to compile, you could just remove the ToString call:

foreach (string eventItem in jsonObject["allEvents"])
{
    ...
}

That will let it compile, but then each item isn't a string - it's an object. In fact, we need to use our knowledge that allEvents is an array. (This API is somewhat poorly designed, IMO...)

JsonArray array = (JsonArray) jsonObject["allEvents"];
foreach (JsonValue eventItem in array)
{
    int id = (int) eventItem["eventId"];
    string type = (string) eventItem["eventType"];
    ...
}

people

See more on this question at Stackoverflow